当我使用Python从标记生成pdf文件时,我遇到了一个问题。我在这里的目标是将我的文档转换成pdf。要做到这一点,我已经有了一个shell命令,如下所示:
markdown <markdown filename>.md | htmldoc --cont --headfootsize 8.0 --linkcolor blue --linkstyle plain --charset utf-8 --format pdf14 - > <pdf filename>.pdf要使用它,您需要安装markdown和htmldoc:
sudo apt-get update
sudo apt-get install markdown
sudo apt-get install htmldoc所以现在我想让这代人自动化。我想在3.6中使用python及其主库subprocess,下面是代码:
import subprocess
import os
import sys
import getopt
import shutil
def list_markdown_file(path):
# this function list all markdown file
# param path = path to the target directory
list_of_file = []
for file in os.listdir(path):
if file.endswith(".md") and not file == 'README.md':
list_of_file.append(os.path.splitext(file)[0])
return list_of_file
def generate_pdf(path, list_file):
destination_dir = "pdf"
if os.path.isdir(os.path.join(path, destination_dir)):
shutil.rmtree(os.path.join(path, destination_dir))
os.mkdir(os.path.join(path, destination_dir))
for filename in list_file:
subprocess.run(["markdown", filename+".md", "|", "htmldoc", "--cont",
"--headfootsize", "8.0", "--linkcolor", "blue", "--linkstyle",
"plain", "--charset", "utf-8", "--format", "pdf14", "-", ">",
os.path.join(path, destination_dir, filename+".pdf")], encoding='utf-8', stdout=subprocess.PIPE)
def main(argv):
try:
opts, args = getopt.getopt(argv, "hp:", ["path"])
except getopt.GetoptError:
print('python generate_pdf.py -p <path_to_directory>')
sys.exit(2)
path_to_file = ''
for opt, arg in opts:
if opt in ('-h', '--help'):
print('python generate_pdf.py -p <path_to_directory>')
sys.exit()
elif opt in ("-p", "--path"):
path_to_file = arg
if not opts:
print('python generate_pdf.py -h to see how its works')
exit(2)
list_of_file = list_markdown_file(path=path_to_file)
generate_pdf(path=path_to_file, list_file=list_of_file)
if __name__ == '__main__':
main(sys.argv[1:])问题就在这一部分:
for filename in list_file:
subprocess.run(["markdown", filename+".md", "|", "htmldoc", "--cont",
"--headfootsize", "8.0", "--linkcolor", "blue", "--linkstyle",
"plain", "--charset", "utf-8", "--format", "pdf14", "-", ">",
os.path.join(path, destination_dir, filename+".pdf")], encoding='utf-8', stdout=subprocess.PIPE)当我这样做时,只运行使用markdown filename.md的部分。为什么会这样呢?我能做些什么来解决这个问题?
发布于 2019-02-18 11:03:55
没有subprocess的shell=True运行一个子进程。如果要运行完整的管道,则需要使用shell=True或单独运行每个进程。
对shell=True的琐碎却没有吸引力
for filename in list_file:
# Switch run([list, of, things]) to (run("string of things", shell=True)
subprocess.run("""markdown '{0}.md' |
htmldoc --cont --headfootsize 8.0 --linkcolor blue --linkstyle plain \\
--charset utf-8 --format pdf14 - >'{1}'""".format(
filename, os.path.join(path, destination_dir, filename+".pdf"),
shell=True)也许稍微更优雅些
for filename in list_file:
with open(os.path.join(path, destination_dir, filename+".pdf")) as dest:
subprocess.run("""markdown '{0}.md' |
htmldoc --cont --headfootsize 8.0 --linkcolor blue --linkstyle plain \\
--charset utf-8 --format pdf14 -""".format(filename),
shell=True, stdout=dest, universal_newlines=True, check=True)您还可以摆脱shell=True并运行两个单独的进程;参见subprocess文档中的换壳管线。
为了说明这一点,subprocess.run(['foo', 'bar', '|' 'baz'])使用参数bar、|和baz运行程序foo;而不是两个进程,其中第二个进程是baz,第二个进程的标准输入连接到第一个进程的标准输出,这是shell在运行管道时所做的。
发布于 2019-02-18 10:57:12
您可以使用名为Markdown2PDF的Python将Markdwen转换为PDF文件,并通过sudo pip3 install Markdown2PDF在Python3中安装它。打开终端,编写像md2pdf <file_name>一样的md2pdf test.md来转换成pdf。
https://stackoverflow.com/questions/54745389
复制相似问题