首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从python生成标记文件的问题

从python生成标记文件的问题
EN

Stack Overflow用户
提问于 2019-02-18 10:41:05
回答 2查看 2.1K关注 0票数 0

当我使用Python从标记生成pdf文件时,我遇到了一个问题。我在这里的目标是将我的文档转换成pdf。要做到这一点,我已经有了一个shell命令,如下所示:

代码语言:javascript
复制
markdown <markdown filename>.md | htmldoc --cont --headfootsize 8.0 --linkcolor blue --linkstyle plain --charset utf-8 --format pdf14 - > <pdf filename>.pdf

要使用它,您需要安装markdown和htmldoc:

代码语言:javascript
复制
sudo apt-get update
sudo apt-get install markdown
sudo apt-get install htmldoc

所以现在我想让这代人自动化。我想在3.6中使用python及其主库subprocess,下面是代码:

代码语言:javascript
复制
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:])

问题就在这一部分:

代码语言:javascript
复制
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的部分。为什么会这样呢?我能做些什么来解决这个问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-18 11:03:55

没有subprocessshell=True运行一个子进程。如果要运行完整的管道,则需要使用shell=True或单独运行每个进程。

shell=True的琐碎却没有吸引力

代码语言:javascript
复制
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)

也许稍微更优雅些

代码语言:javascript
复制
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在运行管道时所做的。

票数 0
EN

Stack Overflow用户

发布于 2019-02-18 10:57:12

您可以使用名为Markdown2PDF的Python将Markdwen转换为PDF文件,并通过sudo pip3 install Markdown2PDF在Python3中安装它。打开终端,编写像md2pdf <file_name>一样的md2pdf test.md来转换成pdf。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54745389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档