def read(*filenames, **kwargs):
"""
Read file contents into string.
Used by setup.py to concatenate long_description.
:param string filenames: Files to be read and concatenated.
:rtype: string
"""
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
if path.splitext(filename)[1] == ".md":
try:
import pypandoc
buf.append(pypandoc.convert_file(filename, 'rst'))
continue
except:
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
return sep.join(buf)
python类convert_file()的实例源码
def long_description(
filename = "README.md"
):
if os.path.isfile(os.path.expandvars(filename)):
try:
import pypandoc
long_description = pypandoc.convert_file(filename, "rst")
except ImportError:
long_description = open(filename).read()
else:
long_description = ""
return long_description
def long_description():
try:
import pypandoc
long_desc = pypandoc.convert_file('README.md', 'rst')
long_desc += '\n' + pypandoc.convert_file('AUTHORS.md', 'rst')
except Exception as e:
print(e)
long_desc = imgkit.__doc__.strip()
return long_desc
def read_md(filename):
try:
from pypandoc import convert_file
return convert_file(filename, 'rst')
except (ImportError, OSError):
return open(filename).read()
def convert_md_to_rst(fp):
try:
import pypandoc
output = pypandoc.convert_file(fp, 'rst')
return output
except ImportError:
warnings.warn('cannot import pypandoc.', UserWarning)
return open(fp).read()
def convert(file, stdin, instanceid):
if stdin:
text = ""
with open(file, 'r') as filehandle:
text = filehandle.read()
# this fails
pypandoc.convert_text(text, "asciidoc",
format="html",
outputfile="%s.asciidoc" % instanceid)
else: # this works
output = pypandoc.convert_file(file, "asciidoc",
format="html")
def printPosts(item, fields, docFormat=None, writeToFiles=False):
template = """+++
{0}
+++
{1}
"""
logger.debug(json.dumps(item,
sort_keys=True,
indent=2,
separators=(',', ': ')))
if docFormat:
logger.debug("Starting to print %s", item['id'])
filename = None
content = item["content"].encode('utf-8', "ignore")
if writeToFiles:
filename = getFilenameFromPostUrl(item['url'], docFormat)
with open(filename, "wb") as outputFile:
outputFile.write(content)
converted = pypandoc.convert_file(
filename,
docFormat,
format="html")
content = template.format(getFrontMatter(item),
converted).encode('utf-8',
'ignore')
with open(filename, "wb") as outputfile:
outputfile.write(content)
else:
print(content)
logger.info("Finished print %s: %s", item['id'], filename)
elif isinstance(fields, basestring):
fields = fields.split(",")
line = [str(item[k]) for k in fields if k in item]
print(",".join(line))
def _load_readme(self):
readme = self._config['package']['readme']
readme_path = os.path.join(self._dir, readme)
if self.has_markdown_readme():
if not pypandoc:
warnings.warn(
'Markdown README files require the pandoc utility '
'and the pypandoc package.'
)
else:
self._readme = pypandoc.convert_file(readme_path, 'rst')
else:
with open(readme_path) as f:
self._readme = f.read()
def makeLongDescription():
return pypandoc.convert_file('README.md', 'rst')
def get_long_description(self, filename='README.md'):
""" I really prefer Markdown to reStructuredText. PyPi does not.
"""
try:
import pypandoc
description = pypandoc.convert_file('README.md', 'rst', 'md')
except (IOError, ImportError):
description = open("README.md").read()
return description
def read_md(f):
return convert_file(f, 'rst')
def long_description(
filename = "README.md"
):
if os.path.isfile(os.path.expandvars(filename)):
try:
import pypandoc
long_description = pypandoc.convert_file(filename, "rst")
except ImportError:
long_description = open(filename).read()
else:
long_description = ""
return long_description
def get_callback(file_meta, user):
def callback(request_id, response, exception):
if exception is None:
file_name = file_meta['name'].replace(' ', '-')
created_time_str = file_meta['createdTime']
created_time = dateutil.parser.parse(created_time_str)
docx_dir = '{0}/{1}/docx'.format(settings.CONVERSION_DIR_ROOT,
user.email)
ensure_dir(docx_dir)
# write response to a docx file
f = open('{0}/{1}.docx'.format(docx_dir, file_name), 'w+')
f.write(response)
f.close()
md_dir = '{0}/{1}/md'.format(settings.CONVERSION_DIR_ROOT,
user.email)
ensure_dir(md_dir)
# construct yaml matter
template = loader.get_template('post_header_template.html')
yaml_matter = template.render({
"title": file_name,
"date": created_time_str,
"categories": ""
})
outputfile = '{0}/{1}-{2}.markdown'.format(md_dir,
created_time.strftime('%Y-%m-%d'),
slugify(file_name))
# convert file
pypandoc.convert_file(
'{0}/{1}.docx'.format(docx_dir, file_name),
'md',
outputfile=outputfile)
# prepend yaml_matter to converted file
# TODO: do this in-place, rather than in-memory
prepend2file(outputfile, yaml_matter)
else:
# handle error
pass
return callback