def save_to_media(request, rst_template, context, format, filename=None): DOCUTILS_FOR = getattr(settings, 'GRIFFIN_DOCUTILS_FOR', []) if (not PANDOC_AVAILABLE) or (format in DOCUTILS_FOR): return save_to_media_docutils(request, rst_template, context, format, filename=None) if not filename: filename = _get_default_filename() final_filename = '%s.%s'%(filename, format) destination = os.path.join(settings.MEDIA_ROOT, 'resume_download') destination_final = os.path.join(destination, final_filename) destination_rst = write_rst(request, rst_template, context, filename) # Finally, convert to the desired format. if format == 'rst': destination_final = destination_rst else: logger.debug("Converting %s to %s (with pandoc)"%( destination_rst, destination_final)) try: pypandoc.convert(destination_rst, format, outputfile=destination_final) except ImportError as ie: logger.error(ie) return None media_link = settings.MEDIA_URL + 'resume_download/' + final_filename logger.debug("Media link for resume is %s"%media_link) return media_link
def format_comment(self, comment): if comment.body == "[deleted]": return pypandoc.convert("[deleted]", "tex", format="md") text = "" text += self.format_comment_header(comment) text += pypandoc.convert(comment.body, "tex", format="md") return text
def test_conversion_with_citeproc_filter(self): if os.environ.get('CI', None): print("Skipping: there is a bug with citeproc on travis.") return # we just want to get a temp file name, where we can write to filters = ['pandoc-citeproc'] written = pypandoc.convert('./filter_test.md', to='html', format='md', outputfile=None, filters=filters) import re as re # only properly converted file will have this in it found = re.search(r'Fenner', written) self.assertTrue(found.group() == 'Fenner') # only properly converted file will have this in it found = re.search(r'10.1038', written) self.assertTrue(found.group() == '10.1038') # make sure that it splits the filter line for filters in ['pandoc-citeproc', u'pandoc-citeproc']: written = pypandoc.convert('./filter_test.md', to='html', format='md', outputfile=None, filters=filters) # only properly converted file will have this in it found = re.search(r'Fenner', written) self.assertTrue(found.group() == 'Fenner') # only properly converted file will have this in it found = re.search(r'10.1038', written) self.assertTrue(found.group() == '10.1038')
def common_setup(src_dir): readme_file = 'README.md' changelog_file = 'CHANGES.md' version_file = 'VERSION' # Convert Markdown to RST for PyPI try: import pypandoc long_description = pypandoc.convert(readme_file, 'rst') changelog = pypandoc.convert(changelog_file, 'rst') except (IOError, ImportError, OSError): long_description = open(readme_file).read() changelog = open(changelog_file).read() # Gather trailing arguments for pytest, this can't be done using setuptools' api if 'test' in sys.argv: PyTest.pytest_args = sys.argv[sys.argv.index('test') + 1:] if PyTest.pytest_args: sys.argv = sys.argv[:-len(PyTest.pytest_args)] PyTest.src_dir = src_dir return dict( # Version is shared between all the projects in this repo version=open(version_file).read().strip(), long_description='\n'.join((long_description, changelog)), url='https://github.com/manahl/pytest-plugins', license='MIT license', platforms=['unix', 'linux'], cmdclass={'test': PyTest}, setup_requires=['setuptools-git'], include_package_data=True )
def ex_edit(request, pk): exercice = get_object_or_404(Exercice, pk=pk) if request.method == "POST": form = ExoForm(request.POST, instance=exercice) if form.is_valid(): exercice = form.save(commit=False) exercice.pub_date = timezone.now() if exercice.enonce_latex: exercice.enonce_html = pypandoc.convert(exercice.enonce_latex,'html5',format='latex',extra_args=['--mathjax','--smart']) if exercice.indication_latex: exercice.indication_html = pypandoc.convert(exercice.indication_latex,'html5',format='latex',extra_args=['--mathjax','--smart']) exercice.save() form.save_m2m() group_name = 'PUBLIC' group = Group.objects.get(name=group_name) perm_codename = 'see_exercice_{0}'.format(pk) perm = get_object_or_404(Permission,codename=perm_codename) if exercice.get_visibility_display() == 'Public': group.permissions.add(perm) elif perm in group.permissions.all(): group.permissions.remove(perm) return redirect('detail', exercice_id=pk) else: form = ExoForm(instance=exercice) return render(request, 'exobase/exercice_edit.html', {'form': form, 'exercice': exercice})
def end_novel(css=None): out_file.close() if css is None: pypandoc.convert(md_file_path, 'html', outputfile=html_file_path, extra_args=['-s']) else: pypandoc.convert(md_file_path, 'html', outputfile=html_file_path, extra_args=['-s', '-c', css]) print('Total words: ' + str(word_count))
def test_unicode_input(self): # make sure that pandoc always returns unicode and does not mishandle it expected = u'üäöîôû{0}======{0}{0}'.format(os.linesep) written = pypandoc.convert(u'<h1>üäöîôû</h1>', 'md', format='html') self.assertTrue(isinstance(written, pypandoc.unicode_type)) self.assertEqualExceptForNewlineEnd(expected, written) bytes = u'<h1>üäöîôû</h1>'.encode("utf-8") written = pypandoc.convert(bytes, 'md', format='html') self.assertEqualExceptForNewlineEnd(expected, written) self.assertTrue(isinstance(written, pypandoc.unicode_type)) # Only use german umlauts in th next test, as iso-8859-15 covers that expected = u'üäö€{0}===={0}{0}'.format(os.linesep) bytes = u'<h1>üäö€</h1>'.encode("iso-8859-15") # Without encoding, this fails as we expect utf-8 per default def f(): pypandoc.convert(bytes, 'md', format='html') self.assertRaises(RuntimeError, f) def f(): # we have to use something which interprets '\xa4', so latin and -1 does not work :-/ pypandoc.convert(bytes, 'md', format='html', encoding="utf-16") self.assertRaises(RuntimeError, f) # with the right encoding it should work... written = pypandoc.convert(bytes, 'md', format='html', encoding="iso-8859-15") self.assertEqualExceptForNewlineEnd(expected, written) self.assertTrue(isinstance(written, pypandoc.unicode_type))
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 test_conversion_from_markdown_with_extensions(self): input = u'~~strike~~' expected_with_extension = u'<p><del>strike</del></p>' expected_without_extension = u'<p><sub><sub>strike</sub></sub></p>' received_with_extension = pypandoc.convert(input, 'html', format=u'markdown+strikeout') received_without_extension = pypandoc.convert(input, 'html', format=u'markdown-strikeout') self.assertEqualExceptForNewlineEnd(expected_with_extension, received_with_extension) self.assertEqualExceptForNewlineEnd(expected_without_extension, received_without_extension)
def do_one_round(): # get all posts from starting point to now now = pytz.utc.localize(datetime.now()) start = get_start(feed_file) print "Collecting posts since %s" % start sys.stdout.flush() posts = get_posts_list(load_feeds(), start) posts.sort() print "Downloaded %s posts" % len(posts) if posts: print "Compiling newspaper" sys.stdout.flush() result = html_head + u"\n".join([html_perpost.format(**nicepost(post)) for post in posts]) + html_tail # with codecs.open('dailynews.html', 'w', 'utf-8') as f: # f.write(result) print "Creating epub" sys.stdout.flush() os.environ["PYPANDOC_PANDOC"] = PANDOC ofile = "dailynews.epub" oofile = "dailynews.mobi" pypandoc.convert( result, to="epub3", format="html", outputfile=ofile, extra_args=["--standalone", "--epub-cover-image=cover.png"], ) print "Converting to kindle" sys.stdout.flush() os.system("%s %s -o %s >/dev/null 2>&1" % (KINDLE_GEN, ofile, oofile)) print "Sending to kindle email" sys.stdout.flush() send_mail( send_from=EMAIL_FROM, send_to=[KINDLE_EMAIL], subject="Daily News", text="This is your daily news.\n\n--\n\n", files=[oofile], ) print "Cleaning up." sys.stdout.flush() os.remove(ofile) os.remove(oofile) print "Finished." sys.stdout.flush() update_start(now)
def end_novel(): out_file.close() pypandoc.convert( md_file_path, "html", outputfile=html_file_path, extra_args=["-s", "-c", "https://mattfister.github.io/nanogenmo2015/samples/base.css"], ) print "Total words: " + str(word_count)
def test_conversion_from_non_plain_text_file(self): with closed_tempfile('.docx') as file_name: expected = u'some title{0}=========={0}{0}'.format(os.linesep) # let's just test conversion (to and) from docx, testing e.g. odt # as well would really be testing pandoc rather than pypandoc received = pypandoc.convert('#some title\n', to='docx', format='md', outputfile=file_name) self.assertEqualExceptForNewlineEnd("", received) received = pypandoc.convert(file_name, to='rst') self.assertEqualExceptForNewlineEnd(expected, received)
def _create(self): args, kwargs = self.get_pandoc_params() try: pypandoc.convert(*args, **kwargs) except: self.errors.append(str("PANDOC-ERROR: " + str(sys.exc_info()))) return self.upload()
def get_description(): if (not os.path.exists("README.txt") or (os.path.exists("README.md") and os.stat("README.txt").st_mtime < os.stat("README.md").st_mtime)): try: import pypandoc pypandoc.convert("README.md", "rst", outputfile="README.txt") except (ImportError, OSError, IOError) as exc: warnings.warn("Markdown to RST conversion failed (%s), using plain markdown for description" % exc) return open("README.md", "rt").read() return open("README.txt", "rt").read()
def sendMandrillMarkdownMail(template, dict): variables = {} for (k, v) in dict["variables"].iteritems(): variables[k+"_html"] = pypandoc.convert(v, "html", format='md') for (elem, style) in dict["styles"].iteritems(): variables[k+"_html"] = variables[k+"_html"].replace("<"+elem+">", "<"+elem+" style=\""+style+"\">"); variables[k+"_txt"] = pypandoc.convert(v, "plain", format='md') sendMandrillMail(template, dict["sender"], dict["recipients"], dict["subject"], variables)
def read_to_rst(fname): try: import pypandoc rstname = "{}.{}".format(os.path.splitext(fname)[0], 'rst') pypandoc.convert(read(fname), 'rst', format='md', outputfile=rstname) with open(rstname, 'r') as f: rststr = f.read() return rststr #return read(rstname) except ImportError: return read(fname)
def test_pdf_conversion(self): tf = tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) name = tf.name tf.close() try: pypandoc.convert('#some title\n', to='pdf', format='md', outputfile=name) except: raise finally: os.remove(name)
def test_conversion_with_markdown_extensions(self): input = '<s>strike</s>' expected_with_extension = u'~~strike~~' expected_without_extension = u'<s>strike</s>' received_with_extension = pypandoc.convert(input, 'markdown+strikeout', format='html') received_without_extension = pypandoc.convert(input, 'markdown-strikeout', format='html') self.assertEqualExceptForNewlineEnd(expected_with_extension, received_with_extension) self.assertEqualExceptForNewlineEnd(expected_without_extension, received_without_extension)
def convert_md_to_rst(source, destination=None, backup_dir=None): """Try to convert the source, an .md (markdown) file, to an .rst (reStructuredText) file at the destination. If the destination isn't provided, it defaults to be the same as the source path except for the filename extension. If the destination file already exists, it will be overwritten. In the event of an error, the destination file will be left untouched.""" # Doing this in the function instead of the module level ensures the # error occurs when the function is called, rather than when the module # is evaluated. try: import pypandoc except ImportError: # Don't give up right away; first try to install the python module. os.system("pip install pypandoc") import pypandoc # Set our destination path to a default, if necessary destination = destination or (os.path.splitext(source)[0] + '.rst') # Likewise for the backup directory backup_dir = backup_dir or os.path.join(os.path.dirname(destination), 'bak') bak_name = (os.path.basename(destination) + time.strftime('.%Y%m%d%H%M%S.bak')) bak_path = os.path.join(backup_dir, bak_name) # If there's already a file at the destination path, move it out of the # way, but don't delete it. if os.path.isfile(destination): if not os.path.isdir(os.path.dirname(bak_path)): os.mkdir(os.path.dirname(bak_path)) os.rename(destination, bak_path) try: # Try to convert the file. pypandoc.convert( source, 'rst', format='md', outputfile=destination ) except: # If for any reason the conversion fails, try to put things back # like we found them. if os.path.isfile(destination): os.remove(destination) if os.path.isfile(bak_path): os.rename(bak_path, destination) raise
def convert_report(templsetting, templfullname, reportsrc, report_fullfilename, pdoc_writer, pdoc_extra_args = []): u"""Inställningar för generering av rapporter via Pandoc""" import pypandoc pdoc_args = (['--smart', '--standalone', '--latex-engine=xelatex', '--columns=60', '--' + templsetting + '=' + templfullname, '--latex-engine-opt=-include-directory=' + templdir] + pdoc_extra_args) pypandoc.convert(reportsrc, pdoc_writer, format = 'md', outputfile = report_fullfilename, extra_args = pdoc_args) if (sys.platform == 'win32' and pdoc_writer == 'docx' and '--toc' in pdoc_args): import subprocess tocscript = os.path.join(maindir, 'toc16.vbs') subprocess.Popen(['wscript', tocscript, report_fullfilename])
def _make_pdf(result, file_object, request): params = { 'date': datetime.now().strftime('%Y-%m-%d'), 'result': result } html = render_to_response('export/cards-export.mako', params, request=request) extra_args = ( '--smart', '--standalone', '--latex-engine=xelatex', '-V', 'mainfont:Linux Libertine O', '-V', 'geometry:top=2cm, bottom=2cm, left=2cm, right=2cm' ) pypandoc.convert(html.body, 'pdf', format='markdown', outputfile=file_object.name, extra_args=extra_args)
def docbook_to_markdown(doc_tag): # We need to convert the element to an XML string # And tostring doesn't like the namespaces for some reason... if doc_tag is None: return None if 'xmlns:map' in doc_tag.attrib: for prefix, namespace in doc_tag.attrib['xmlns:map'].iteritems(): ET.register_namespace(prefix, namespace) del doc_tag.attrib['xmlns:map'] for e in doc_tag.iter(): if 'xmlns:map' in e.attrib: del e.attrib['xmlns:map'] doc_tag_source = ET.tostring(doc_tag) markdown = pypandoc.convert(doc_tag_source, 'markdown_github', format="docbook") return pypandoc.convert(doc_tag_source, 'markdown_github', format="docbook")
def pandoc_tofile(self, oformat, addarg=None): filters, arguments = self.get_pandoc_args() if addarg: arguments.append(addarg) pypandoc.convert(self.text, to=oformat, format="md", extra_args=arguments, filters=filters, outputfile=self.exportpath) self.show_file()
def readme(): try: import pypandoc return pypandoc.convert(source='README.md', to='rst') except: with open('README.md') as f: return f.read()
def generate(name, oformat): tformat = oformat if oformat == 'pdf': tformat = 'latex' conn = sqlite3.connect( DBFILE ) db = conn.cursor() presentation = db.execute('SELECT title,author,text FROM presentations WHERE name=?', (name,) ).fetchone() p_title = presentation[0] p_author = presentation[1] p_text = presentation[2] rows = db.execute('SELECT slide,title,text FROM slides WHERE name=?', (name,) ).fetchall() new_rows = [] for row in rows: new_row = (row[0], row[1], pypandoc.convert(row[2], tformat, format='markdown')) new_rows.append(new_row) rows = new_rows tpl = 'slides.' + oformat result = template(tpl, name=name, rows=rows, p_title=p_title, p_author=p_author) if oformat == 'html': return result elif oformat == 'pdf': result = latex2pdf(result) response.content_type = 'application/pdf' return result elif oformat == 'latex': response.content_type = 'text/plain; charset=utf-8' return result
def translate_for_github(content): if not content: return None output = pypandoc.convert(content, 'markdown_github', format='textile') return output
def to_taskwarrior(self): record = { 'project': re.sub(r'\W+', '-', self.record['project']).lower(), 'priority': self.get_priority(), 'annotations': self.extra.get('annotations', []), self.NAME: self.record.get('name', ''), self.BODY: pypandoc.convert(self.record.get('body'), 'md', format='html').rstrip(), self.PERMALINK: self.record['permalink'], self.TASK_ID: int(self.record.get('task_id')), self.PROJECT_NAME: self.record['project'], self.PROJECT_ID: int(self.record['project_id']), self.FOREIGN_ID: int(self.record['id']), self.TYPE: self.record.get('type', 'subtask').lower(), self.CREATED_BY_NAME: self.record['created_by_name'], self.MILESTONE: self.record['milestone'], self.ESTIMATED_TIME: self.record.get('estimated_time', 0), self.TRACKED_TIME: self.record.get('tracked_time', 0), self.LABEL: self.record.get('label'), } if self.TYPE == 'subtask': # Store the parent task ID for subtasks record['actaskid'] = int(self.record['task_id']) if isinstance(self.record.get('due_on'), dict): record['due'] = self.parse_date( self.record.get('due_on')['formatted_date'] ) if isinstance(self.record.get('created_on'), dict): record[self.CREATED_ON] = self.parse_date( self.record.get('created_on')['formatted_date'] ) return record
def markdown2rst(path): try: import pypandoc return pypandoc.convert(path, 'rst', 'md') except ImportError: with open(path, 'r') as f: return f.read()
def readme(): try: import pypandoc return pypandoc.convert('README.md', 'rst', format='md') except (IOError, ImportError): with open('README.md') as f: return f.read()
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()
from setuptools import setup, find_packages # Always prefer setuptools over distutils from codecs import open # To use a consistent encoding import os base_dir = os.path.abspath(os.path.dirname(__file__)) about = {} with open(os.path.join(base_dir, "nihts_xcam", "__about__.py")) as f: exec(f.read(), about) # Get the long description from the relevant file, converting from md to rst if possible with open(os.path.join(base_dir, 'README.md'), encoding='utf-8') as f: long_description = f.read() try: from pypandoc import convert long_description = convert('README.md', 'rst', format='md') except ImportError: print("warning: pypandoc module not found, could not convert Markdown to RST") setup( name=about["__title__"], # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version=about["__version__"], description=about["__summary__"], long_description=long_description,
#!/usr/bin/env python # http://stackoverflow.com/questions/9810603/adding-install-requires-to-setup-py-when-making-a-python-package try: from setuptools import setup except ImportError: from distutils.core import setup try: import pypandoc try: LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst') except: # Catch all exceptions because FileNotFoundError is only in 3.x from pypandoc.pandoc_download import download_pandoc download_pandoc() LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst') except ImportError: with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() setup(name='molml', version='0.8.0', description='An interface between molecules and machine learning', long_description=LONG_DESCRIPTION, author='Chris Collins', author_email='*****@*****.**', url='https://github.com/crcollins/molml/', license='MIT', packages=['molml'], test_suite='nose.collector',
# __version__ = 'ver' version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") try: import pypandoc # Strip Markdown image tags from README.md and convert to rst long_description = '%s\n%s' % ( re.compile('^\[!\[.*$', re.M).sub('', read('README.md')), re.sub(':[a-z]+:`~?(.*?)`', r'``\1``', read('CHANGELOG.md')) ) long_description = pypandoc.convert( long_description.lstrip('\n'), 'rst', format='md') long_description = long_description.replace('\r\n', '\n') except (ImportError, OSError): # pandoc is not installed, fallback to using raw contents print("WARNING: Pandoc not found. Long_description conversion failure. " "Do not upload this package to pypi.") with io.open('README.md', encoding="utf-8") as f: long_description = f.read() setup( name='pyro', version=find_version('src', 'pyro', '__init__.py'), license="Apache Software License 2.0", description='An example package. Generated with cookiecutter-pyro.', long_description=long_description,
re.MULTILINE).group(1) classifiers = [ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: PyPy' ] try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): long_description = open('README.md').read() setup(name='aliyun-log-python-sdk', version=version, description='Aliyun log service Python client SDK', author='Aliyun', url='https://github.com/aliyun/aliyun-log-python-sdk', install_requires=install_requires, packages=packages, classifiers=classifiers, long_description=long_description)
import os import sys from setuptools import setup # Set external files try: from pypandoc import convert README = convert('README.md', 'rst') except ImportError: README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as f: required = f.read().splitlines() with open(os.path.join(os.path.dirname(__file__), 'test_requirements.txt')) as f: test_required = f.read().splitlines() setup( name='zappa', version='0.35.1', packages=['zappa'], install_requires=required, tests_require=test_required, test_suite='nose.collector', include_package_data=True, license='MIT License', description= 'Server-less Python Web Services for AWS Lambda and API Gateway', long_description=README, url='https://github.com/Miserlou/Zappa',
# if os.path.isfile(page + ".html") is False: # html_text = get_page(page) # # If there's a / ... # new_page = page.replace('/', '_') # html_f = open("{}.html".format(new_page), 'w') # html_f.write(html_text) # Convert for page in pages: # page = page.replace('/', '_') f = open(page) html_text = f.read() # Various replacements that pandoc does not do print("Converting {}".format(page)) #html_text = html_text.replace('<perl>', '\n```perl\n') #html_text = html_text.replace('</perl>', '\n```\n') #html_text = html_text.replace("\\n", "\n") md_text = pypandoc.convert(html_text, 'markdown_github', format='html') # Correct some conversion errors #md_text = md_text.replace('\\\\', '') #md_text = md_text.replace('1. !', '#!') #md_text = md_text.replace('\\`\\`\\`', '```') #md_text = md_text.replace('\\_', '_') md_page = page.replace('.html', '') md_f = open("{}.md".format(page), 'w') md_f.write(md_text)
if os.path.exists(targettex) and not args.overwrite: raise IOError("target file " + targettex + " exists -- will not overwrite it") # make sure the parent directory exists try: os.makedirs(os.path.abspath(os.path.join(targettex, os.pardir))) except OSError as e: if e.errno != errno.EEXIST: raise # retrieve page and write to disk page = wptools.page(args.page, lang=args.language).get_parse().get_more() with open(targettex, 'w') as o: o.write( pypandoc.convert(page.data['wikitext'], "latex", format="mediawiki")) # download files if --imagedir was provided if "files" in page.data and args.imagedir is not None: # make sure imagedir is a directory if given try: os.makedirs(args.imagedir) except OSError as e: if e.errno != errno.EEXIST: raise for image in page.data['files']: print("downloading " + image) colon = image.find(":") if colon < 2: raise RuntimeError("cannot find a colon in " + image)
# is installed here PY2 = (sys.version_info.major == 2) readme_dir = os.path.dirname(__file__) readme_filename = os.path.join(readme_dir, 'README.md') try: with open(readme_filename, 'r') as f: readme = f.read() except: logging.warn("Failed to load %s" % readme_filename) readme = "" try: import pypandoc readme = pypandoc.convert(readme, to='rst', format='md') except: logging.warn("Conversion of long_description from MD to RST failed") pass with open('mhcflurry/__init__.py', 'r') as f: version = re.search( r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1) if __name__ == '__main__': required_packages = [ 'six', 'numpy>=1.11',
import os from setuptools import setup try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print( "warning: pypandoc module not found, could not convert Markdown to RST" ) read_md = lambda f: open(f, 'r').read() from gelfclient import __version__ setup( name="gelfclient", version=__version__, author="Chris McClymont", author_email="*****@*****.**", description= "A UDP client for sending message in the Graylog Extended Log Format (GELF)", license="Apache v2", keywords="gelf, graylog, graylog2, logging", url="http://github.com/orionvm/python-gelfclient", packages=['gelfclient'], long_description=read_md('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "Topic :: System :: Logging" ], setup_requires=['six>=1.10'], install_requires=[
def convert_md(source): try: from pypandoc import convert return convert(source, "rst", format="md", encoding="utf8") except (ImportError, OSError): return source
#!/usr/bin/env python import setuptools from setuptools import setup try: import pypandoc # pypandoc.download_pandoc() read_md = lambda f: pypandoc.convert(f, 'rst') except ImportError: print( "warning: pypandoc module not found, could not convert Markdown to RST" ) read_md = lambda f: open(f, 'r').read() setup(name='chess_py', version='3.3.0', description='Python chess client', long_description=read_md("README.md"), platforms='MacOS X, Windows, Linux', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 2.7', ], author='Aubhro Sengupta', author_email='*****@*****.**', url='https://github.com/LordDarkula/chess_py', license='MIT', packages=setuptools.find_packages())
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() try: from pypandoc import convert read_md = lambda f: convert(f, "rst").replace("\r", "") except (ImportError, IOError): print( "warning: pypandoc module not found, could not convert Markdown to RST" ) read_md = lambda f: read(f) setup(author="Pinax Team", author_email="*****@*****.**", description="a document management app for Django", name="pinax-documents", long_description=read_md("README.md"), version="0.5.0", url="http://github.com/pinax/pinax-documents/", license="MIT", packages=find_packages(), package_data={"documents": []},
def read_md(fpath): return convert(fpath, 'rst')
import sys from setuptools import setup, find_packages # require pypandoc conversion for upload if 'upload' in sys.argv[1:]: import pypandoc README = pypandoc.convert('README.md', 'rst') else: README = open('README.md').read() setup( name='django-registration-invite', version='0.0.3', description='HMAC-based invitation backend for django-registration', long_description=README, author='Ryan P Kilby', author_email='*****@*****.**', keywords='django-registration invitation invite', url='https://github.com/rpkilby/django-registration-invite/', packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, install_requires=[], license='BSD License', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.11', 'Framework :: Django :: 2.0',
def read_md(readme_file): return convert(readme_file, 'rst')
os.unlink(os.path.join(dirpath, filename)) continue # libs if extension in ('.c', '.h'): pyx_file = str.replace(filename, extension, '.pyx') if os.path.exists(os.path.join(dirpath, pyx_file)): print("Remove", filename) os.unlink(os.path.join(dirpath, filename)) # Readme readme_filepath = os.path.join(os.path.dirname(__file__), "README.md") try: import pypandoc long_description = pypandoc.convert(readme_filepath, 'rst') except ImportError: long_description = open(readme_filepath).read() # Windows build_cmake_args = list() if os.getenv("WIN_BUILD"): build_cmake_args.append('-DUSE_WIN_DEP=ON') if os.getenv("VCPKG_BUILD"): build_cmake_args.append('-DUSE_VCPKG=ON') build_cmake_args.append('-DCMAKE_TOOLCHAIN_FILE={}'.format( os.getenv("VCPKG_TOOLCHAIN"))) # setup needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv) pytest_runner = [
import os from setuptools import setup version = '0.0.1' def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() try: import pypandoc README = pypandoc.convert('README.md', 'rst') CHANGES = pypandoc.convert('CHANGES.md', 'rst') except: README = read('README.md') CHANGES = read('CHANGES.md') setup( name='pyteamcity', version=version, description='Use the TeamCity REST API from Python', long_description='%s\n\n%s' % (README, CHANGES), url='https://github.com/SurveyMonkey/pyteamcity', author='Yotam Oron', author_email='*****@*****.**', py_modules=['pyteamcity'], zip_safe=False, install_requires=['beautifulsoup4', 'requests'], license='MIT', classifiers=[ 'Programming Language :: Python :: 2',
def read_md(f): return convert(f, 'rst')
# string in below ... def get_path(fname): return os.path.join(os.path.dirname(os.path.abspath(__file__)), fname) def read(fname): return open(get_path(fname)).read() packages = find_packages() try: import pypandoc long_description = pypandoc.convert(get_path('README.md'), 'rst') long_description = long_description.split( '<!---Illegal PyPi RST data -->')[0] f = open(get_path('README.rst'), 'w') f.write(long_description) f.close() print("Successfully converted README.md to README.rst") except (IOError, ImportError): # No long description... but nevermind, it's only for PyPi uploads. long_description = "" setup( name="django-nyt", version=VERSION, author="Benjamin Bach", author_email="*****@*****.**",
"""A setuptools based setup module.""" # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file readme = path.join(here, 'README.md') try: # To convert md to rst import pypandoc long_description = pypandoc.convert(readme, 'rst') except (IOError, ImportError): long_description = "" setup( name='alkivi-config-manager', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='1.2.8', description='Python config-manager used at Alkivi', long_description=long_description, # The project's main homepage. url='https://github.com/alkivi-sas/python-alkivi-config-manager',
# extension version version = get_version() cmdclass = { 'build_manpage': BuildManPage, 'build_examples': BuildRSTExamplesFromScripts, } # PyPI doesn't render markdown yet. Workaround for a sane appearance # https://github.com/pypa/pypi-legacy/issues/148#issuecomment-227757822 README = opj(dirname(__file__), 'README.md') try: import pypandoc long_description = pypandoc.convert(README, 'rst') except (ImportError, OSError) as exc: # attempting to install pandoc via brew on OSX currently hangs and # pypandoc imports but throws OSError demanding pandoc print( "WARNING: pypandoc failed to import or thrown an error while converting" " README.md to RST: %r .md version will be used as is" % exc) long_description = open(README).read() requires = { 'core': [ 'datalad>=0.12', 'requests>=1.2', # to talk to Singularity-hub 'mock', # used in containers_run ], 'devel-docs': [
from setuptools import setup import re with open('osmapi/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') try: import pypandoc from unidecode import unidecode description = open('README.md', encoding='utf-8').read() description = unidecode(description) description = pypandoc.convert(description, 'rst', format='md') except (IOError, OSError, ImportError): description = 'Python wrapper for the OSM API' setup( name='osmapi', packages=['osmapi'], version=version, install_requires=['requests'], description='Python wrapper for the OSM API', long_description=description, author='Etienne Chové', author_email='*****@*****.**', maintainer='Stefan Oderbolz', maintainer_email='*****@*****.**', url='https://github.com/metaodi/osmapi',
for title, entries in bib_df.groupby('title', sort=False): entries = entries.sort('ENTRYTYPE') main_entry = entries.iloc[0] sys.stdout.write('## ' + main_entry['title'] + '\n') write_comma = False for author in main_entry['author'].split(' and '): if write_comma: sys.stdout.write(', ') write_comma = True author = pypandoc.convert(author, 'html', format='latex') author = author.replace('<p>', '').replace('</p>', '') author = author.replace('<span>', '').replace('</span>', '') author = author.rstrip() last, first = author.split(', ') first = ''.join([a[0] for a in first.split(' ')]) author = ' '.join([last, first]) author = namedentities.numeric_entities(author) if last.lower() == 'mcpherson' and first.lower().startswith('a'): sys.stdout.write('__{0}__'.format(author)) else: sys.stdout.write('{0}'.format(author)) sys.stdout.write(' \n')
more_requires = [] if os.getenv('STDEB_BUILD') not in ['1', 'true']: more_requires.extend( ['doppel >= 0.4.0', 'pysetenv;platform_system=="Windows"']) if os.getenv('NO_PATCHELF') not in ['1', 'true']: more_requires.append('patchelf-wrapper;platform_system=="Linux"') with open(os.path.join(root_dir, 'README.md'), 'r') as f: # Read from the file and strip out the badges. long_desc = re.sub(r'(^# bfg9000.*)\n\n(.+\n)*', r'\1', f.read()) try: import pypandoc long_desc = pypandoc.convert(long_desc, 'rst', format='md') except ImportError: pass setup( name='bfg9000', version=version, description='A cross-platform build file generator', long_description=long_desc, keywords='build file generator', url='https://jimporter.github.io/bfg9000/', author='Jim Porter', author_email='*****@*****.**', license='BSD', classifiers=[ 'Development Status :: 3 - Alpha',
PKG_URL="https://github.com/piqueserver/piqueserver" PKG_DOWNLOAD_URL="https://github.com/piqueserver/piqueserver/archive/0.1.0.zip" extra_args = sys.argv[2:] import subprocess import shutil from setuptools import setup, find_packages, Extension, dist from distutils.core import run_setup try: import pypandoc import re long_description = pypandoc.convert_text( re.sub(r'[^\x00-\x7F]+',' ', pypandoc.convert('README.md', 'markdown', format="markdown_github")), 'rst', format="markdown") except (IOError, ImportError): long_description = '' ext_modules = [] names = [ 'pyspades.vxl', 'pyspades.bytes', 'pyspades.packet', 'pyspades.contained', 'pyspades.common', 'pyspades.world', 'pyspades.loaders', 'pyspades.mapmaker'
from setuptools import setup, find_packages readme_dir = os.path.dirname(__file__) readme_path = os.path.join(readme_dir, 'README.md') try: with open(readme_path, 'r') as f: readme_markdown = f.read() except: print("Failed to load README file") readme_markdown = "" try: import pypandoc readme_restructured = pypandoc.convert(readme_markdown, to='rst', format='md') except: readme_restructured = readme_markdown print( "Conversion of long_description from markdown to reStructuredText failed, skipping..." ) with open('pepdata/__init__.py', 'r') as f: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1) if __name__ == '__main__': setup( name='pepdata', version=version,
def read_long_description(): try: import pypandoc return pypandoc.convert('README.md', 'rst') except (IOError, ImportError, RuntimeError): return ""
log.info("COMPILER_ARGS=" + " ".join(COMPILER_ARGS)) log.info("EXTRA_LINK_ARGS=" + " ".join(EXTRA_LINK_ARGS)) log.info("RUNTIME_LIB_DIRS=" + " ".join(RUNTIME_LIB_DIRS)) _build_ext.run(self) if os.path.abspath(".") != SCRIPT_DIR: log.info("Copying built extensions...") for d in os.listdir("build"): target_dir = os.path.join(SCRIPT_DIR, "build", d) rmtree(target_dir, ignore_errors=True) copytree(os.path.join("build", d), target_dir) os.chdir(ORIG_DIR) try: import pypandoc long_description = pypandoc.convert("README.md", "rst") except: long_description = "" setup( name="dyNET", # version="0.0.0", install_requires=["cython", "numpy"], description="The Dynamic Neural Network Toolkit", long_description=long_description, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Environment :: MacOS X", "Environment :: Win32 (MS Windows)", "Intended Audience :: Developers",
import re version = re.search('^__version__\s*=\s*"(.*)"', open('ldndc2nc/ldndc2nc.py').read(), re.M).group(1) here = path.abspath(path.dirname(__file__)) # Get the long description from the README file #with open("README.md", "rb") as f: # long_descr = f.read().decode("utf-8") # Auto convert md to rst for PyPI readme_file = 'README.md' try: from pypandoc import convert long_descr = convert(readme_file, 'rst', 'md') with open(path.join(here, 'README.rst'), 'w', encoding='utf-8') as f: f.write(long_descr) except ImportError: print( "warning: pypandoc module not found, could not convert Markdown to RST" ) long_descr = open(readme_file).read() # get the dependencies and installs with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f: all_reqs = f.read().split('\n') install_requires = [x.strip() for x in all_reqs if 'git+' not in x] dependency_links = [ x.strip().replace('git+', '') for x in all_reqs if 'git+' not in x
https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) ## Trick to use MarkDown, and still supply Pypi with RST ## from: https://stackoverflow.com/a/23265673 try: from pypandoc import convert read_md = lambda f: convert(f, 'rst').replace('\r\n', '\n') except ImportError: print( "warning: pypandoc module not found, could not convert Markdown to RST" ) read_md = lambda f: open(f, 'r').read() long_description = read_md(path.join(here, 'README.md')) print(repr(long_description)) setup( name='subprocess_maximize', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html