我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用pypandoc.convert()。
def create_readme_with_long_description(): this_dir = os.path.abspath(os.path.dirname(__file__)) readme_md = os.path.join(this_dir, 'README.md') readme = os.path.join(this_dir, 'README') if os.path.isfile(readme_md): if os.path.islink(readme): os.remove(readme) shutil.copy(readme_md, readme) try: import pypandoc long_description = pypandoc.convert(readme_md, 'rst', format='md') if os.path.islink(readme): os.remove(readme) with open(readme, 'w') as out: out.write(long_description) except(IOError, ImportError, RuntimeError): if os.path.isfile(readme_md): os.remove(readme) os.symlink(readme_md, readme) with open(readme, encoding='utf-8') as in_: long_description = in_.read() return long_description
def convert(self, from_extension, to_extension): config=get_pandoc_config(from_extension, to_extension) self.converted_file_name='{filename}.{extension}'.format( filename=self.file_name, extension=config['to_extension']) file_path=os.path.join(self.file_directory, self.file_name) converted_file_path=os.path.join( self.converted_file_directory, self.converted_file_name) pypandoc.convert( source=file_path, format=config['from_format'], to=config['to_format'], outputfile=converted_file_path, extra_args=config['extra_args']) return get_mimetype(converted_file_path)
def read_md(readme_file): return convert(readme_file, 'rst')
def get_long_description(): """Reads the long description from the README""" try: import pypandoc return pypandoc.convert('README.md', 'rst') except Exception as ex: print("Unable to convert README to RST: '{}'".format(ex)) return ""
def read_md(f): return convert(f, 'rst')
def get_long_description(f): try: import pypandoc except ImportError: return 'No description' return pypandoc.convert(f, 'rst')
def read_md(file): try: # noinspection PyPackageRequirements,PyUnresolvedReferences from pypandoc import convert return convert(file, 'rst', 'md') except ImportError: import warnings warnings.warn('pypandoc module not found, could not convert Markdown to RST') with open(file, 'r') as md: return md.read()
def readme(): """ Reads the readme file and converts it to RST if pypandoc is installed. If not, the raw markdown text is returned :return: the readme file as a string """ # noinspection PyBroadException try: # noinspection PyPackageRequirements,PyUnresolvedReferences import pypandoc with open("README.md") as f: # Convert markdown file to rst markdown = f.read() rst = pypandoc.convert(markdown, "rst", format="md") return rst except ModuleNotFoundError: # If pandoc is not installed, just return the raw markdown text with open("README.md") as f: return f.read()
def readme(): try: import pypandoc return pypandoc.convert(source='README.md', to='rst') except: with open('README.md') as f: return f.read()
def read_readme(): try: import pypandoc return pypandoc.convert('README.md', 'rst') except ImportError: with open(os.path.join(here, 'README.md')) as f: return f.read()
def read(fname): """ Read filename. :param str fname: name of a file to read """ return convert(os.path.join(here, fname), 'rst')
def _make_note(self, note_data): """ Converts a note from HTML to the configured markup. If the note was previously edited with zotcli, the original markup will be restored. If it was edited with the Zotero UI, it will be converted from the HTML via pandoc. :param note_html: HTML of the note :param note_version: Library version the note was last edited :returns: Dictionary with markup, format and version """ data = None note_html = note_data['data']['note'] note_version = note_data['version'] if "title=\"b'" in note_html: # Fix for badly formatted notes from an earlier version (see #26) note_html = re.sub(r'title="b\'(.*?)\'"', r'title="\1"', note_html) note_html = note_html.replace("\\n", "") blobs = DATA_PAT.findall(note_html) # Previously edited with zotcli if blobs: data = decode_blob(blobs[0]) if 'version' not in data: data['version'] = note_version note_html = DATA_PAT.sub("", note_html) # Not previously edited with zotcli or updated from the Zotero UI if not data or data['version'] < note_version: if data and data['version'] < note_version: self._logger.info("Note changed on server, reloading markup.") note_format = data['format'] if data else self.note_format data = { 'format': note_format, 'text': pypandoc.convert( note_html, note_format, format='html'), 'version': note_version} return data
def _make_note_html(self, note_data): """ Converts the note's text to HTML and adds a dummy element that holds the original markup. :param note_data: dict with text, format and version of the note :returns: Note as HTML """ extra_data = DATA_TMPL.format( data=encode_blob(note_data).decode('utf8')) html = pypandoc.convert(note_data['text'], 'html', format=note_data['format']) return html + extra_data
def convert_readme_to_rst(): """ Attempt to convert a README.md file into README.rst """ project_files = os.listdir('.') for filename in project_files: if filename.lower() == 'readme': raise ProjectError( 'found {} in project directory...'.format(filename) + 'not sure what to do with it, refusing to convert' ) elif filename.lower() == 'readme.rst': raise ProjectError( 'found {} in project directory...'.format(filename) + 'refusing to overwrite' ) for filename in project_files: if filename.lower() == 'readme.md': rst_filename = 'README.rst' logger.info('converting {} to {}'.format(filename, rst_filename)) try: rst_content = pypandoc.convert(filename, 'rst') with open('README.rst', 'w') as rst_file: rst_file.write(rst_content) return except OSError as e: raise ProjectError( 'could not convert readme to rst due to pypandoc error:' + os.linesep + str(e) ) raise ProjectError('could not find any README.md file to convert')
def pandoc_convert(app, unused_a, unused_b, unused_c, unused_d, lines): if not lines: return input_format = app.config.pandoc_use_parser data = '\n'.join(lines).encode('utf-8') data = pypandoc.convert(data, 'rst', format=input_format) new_lines = data.split('\n') del lines[:] lines.extend(new_lines)
def release(*setup_commands): markdown_file = os.path.join(base_dir, 'README.md') rst_file = os.path.join(base_dir, 'README.rst') rst_content = pypandoc.convert(markdown_file, 'rst') with open(rst_file, 'wb') as f: f.write(rst_content.encode('utf-8')) run('python setup.py {}'.format(' '.join(setup_commands))) os.unlink(rst_file)
def get_readme(): try: import pypandoc readme_data = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): readme_data = open('README.md').read() return readme_data
def get_long_description(): with open(os.path.join(ROOT, 'README.md'), encoding='utf-8') as f: markdown_txt = f.read() try: import pypandoc long_description = pypandoc.convert(markdown_txt, 'rst', format='md') except(IOError, ImportError): logging.warning("Could not import package 'pypandoc'. Will not convert markdown readme to rst for PyPI.") long_description = markdown_txt return long_description
def readme(): try: import pypandoc description = pypandoc.convert('README.md', 'rst') except: description = '''Configuration.py is a library for configuration management in python apps. Its goal is to make configurations management as human-friendly as possible. It provides a simple `load` function that allows to load configuration for given environment from any supported formats.''' return description
def get_long_description(): try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): with open('README.txt') as fhan: long_description = fhan.read() return long_description
def read_long_description(readme_file): """ Read package long description from README file """ try: import pypandoc except (ImportError, OSError) as exception: print('No pypandoc or pandoc: %s' % (exception,)) if sys.version_info.major == 3: handle = open(readme_file, encoding='utf-8') else: handle = open(readme_file) long_description = handle.read() handle.close() return long_description else: return pypandoc.convert(readme_file, 'rst')
def read_md(f): try: from pypandoc import convert return convert(f, 'rst') except ImportError: return open(f, 'r').read()
def readme(): # I really prefer Markdown to reStructuredText. PyPi does not. This allows me # to have things how I'd like, but not throw complaints when people are trying # to install the package and they don't have pypandoc or the README in the # right place. # From https://coderwall.com/p/qawuyq/use-markdown-readme-s-in-python-modules try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): with open('README.md') as f: return f.read() else: return long_description
def convert_wiki_to_table(wiki_text, n_table=0): html_text = pypandoc.convert(wiki_text, 'html', 'mediawiki') tables = pandas.read_html(html_text) return tables[n_table]
def read_md(path): try: import pypandoc return pypandoc.convert(path, 'rst') except ImportError: return open(path).read()
def readme(): try: import pypandoc return pypandoc.convert('README.md', 'rst') except: with open('README.md') as f: return f.read()
def read_markdown(file): return convert(file, "rst")
def to_html(text): pandoc_args = [ '--mathjax', '--smart', ] raw_html = pypandoc.convert(text, 'html', format='md', extra_args=pandoc_args) html = bleach.clean(raw_html, print_tags, print_attrs, all_styles) return mark_safe(html)
def convert(filename, fmt): with io.open(filename, encoding='utf-8') as fd: return fd.read()
def run(self): # verify that we can actually do the converstion import pypandoc long_description = pypandoc.convert('README.md', 'rst') sdist.run(self) # pypi does not render markdown. # https://stackoverflow.com/a/26737672/19741
def get_long_description(): """Get long description used on PyPI project page.""" try: # Use pandoc to create reStructuredText README if possible import pypandoc return pypandoc.convert('README.md', 'rst') except: return None
def readme(): with open('README.md', 'r') as f: readme_md = f.read() if pypandoc: readme_rst = pypandoc.convert(readme_md, 'rst', format='md') return readme_rst else: return readme_md
def html2latex(text): output = pypandoc.convert(text, 'latex', format='html', extra_args=['-f', 'html+tex_math_dollars']) return output
def main(): """render the docs""" # make sure we're in the right place cwd = os.getcwd() seg = os.path.split(cwd) if seg[1] != 'docs': print('must be run in pypond/docs as ./rebuild_docs.py') return -1 # regenerate the module api index subprocess.call(['sphinx-apidoc', '-f', '-o', 'source', '../pypond/']) # generate a new index including the README.md # shave off the first line RE: badges to be displayed # on github but shaved off for the get the docs stuff. with open('../README.md', 'r') as fh: data = ''.join(fh.readlines()[1:]) readme = pypandoc.convert(data, 'rst', format='md') index_text = RST_INDEX.replace('README_TOKEN', readme) index_file = './source/index.rst' if not os.path.exists(index_file): print('can not find {f}'.format(f=index_file)) return -1 fh = open(index_file, 'w') fh.write(index_text) fh.close()
def readme(): try: import pypandoc except ImportError: return '' return pypandoc.convert('README.md', 'rst')
def convert_md(): with open(RST_README_PATH, 'w') as readme: readme.write(convert(MD_README_PATH, 'rst'))
def read(path): """Convert Markdown to reStructuredText if possible.""" with open(path) as file_object: text = file_object.read() try: import pypandoc return pypandoc.convert(text, 'rst', 'md') except ImportError: return text # allow setup.py to be run from any path
def convert_figure(self): r""" This uses pandoc to convert the explicit table text only. """ pandoc_args = ["--mathjax"] try: converted_table = pypandoc.convert_text( self.table_text, to='markdown', format='latex', extra_args = pandoc_args) except AttributeError: # for pypandoc version before 1.2 converted_table = pypandoc.convert( self.table_text, to='markdown', format='latex', extra_args=pandoc_args) if self.label_text: this_label = self.label_text else: this_label = "tbl:" + self.uid converted_caption = ": {} {{#{}}}".format(self.caption_text.replace("\n", " "), this_label) self.output_content = "{}{}".format(converted_table, converted_caption)
def read_md(f): try: from pypandoc import convert try: return convert(os.path.join(THIS_DIR, f), 'rst') except: return "GeomEppy" except ImportError: print("warning: pypandoc module not found, could not convert Markdown to RST") try: with open(os.path.join(THIS_DIR, f), 'r') as f_in: return f_in.read() except: return "GeomEppy"
def render_doc_(notebook, output_format, output_file, template, extra_args): """""" pypandoc.convert( source=template.render(notebook), to="pdf" if output_format == "pdf" else output_format, format="markdown-blank_before_header", outputfile=output_file, extra_args=extra_args )
def readme(): with open(path.join(path.abspath(path.dirname(__file__)), 'README.md')) as f: try: from pypandoc import convert return convert(f.read(), 'rst', 'md') except ImportError: return f.read()
def main(): # check we're on master assert b'* master' in subprocess.check_output(['git', 'branch']), 'Not on master branch' # check we're up-to-date status = subprocess.check_output(['git', 'status']) assert b'modified' not in status, 'Repository contains modified files' assert b'Untracked' not in status, 'Repository contains untracked files' # increment version version = __version__ major, minor, patch = version.split('.') new_version = '%s.%s.%d' % (major, minor, int(patch) + 1) replace('geomeppy/__init__.py', version, new_version) replace('setup.py', "version='%s'" % version, "version='%s'" % new_version) replace('setup.py', "tarball/v%s" % version, "tarball/v%s" % new_version) try: # convert docs to rst z = pypandoc.convert('README.md', 'rst', format='markdown') with open('README.rst', 'w') as outfile: outfile.write(z) # add and commit changes print(subprocess.check_output(['git', 'add', 'geomeppy/__init__.py'])) print(subprocess.check_output(['git', 'add', 'setup.py'])) print(subprocess.check_output(['git', 'add', 'README.rst'])) print(subprocess.check_output(['git', 'commit', '-m', 'release/%s' % new_version])) except Exception as e: # rollback print('rolling back') print(e) replace('geomeppy/__init__.py', new_version, version) replace('setup.py', new_version, version) exit() try: # create a tagged release print(subprocess.check_output(['git', 'tag', '-m', 'release/%s' % new_version, 'v%s' % new_version])) # push to github print(subprocess.check_output(['git', 'push', 'origin', 'master', '-f'])) # create dist print(subprocess.check_output(['python', 'setup.py', 'sdist'])) # release except Exception as e: # rollback print('rolling back tag') print(e) # delete the tagged release print(subprocess.check_output(['git', 'tag', '-d', 'release/%s' % new_version, 'v%s' % new_version])) # push to github print(subprocess.check_output( ['git', 'push', 'origin', ':refs/tags/release/%s' % new_version, 'v%s' % new_version]) ) exit() try: print(subprocess.check_output(['twine', 'upload', 'dist/geomeppy-%s.tar.gz' % new_version])) except Exception as e: print('too late to roll back') print(e) exit()