繁体   English   中英

使用 subprocess.Popen 从 python 调用 pandoc

[英]Calling pandoc from python using subprocess.Popen

我有打电话从使用python pandoc问题subprocess.Popen 这一切都在控制台中工作。 这是代码。

# Test markdown file
here is just a simple markdown file.

现在我使用该filename python代码是我的markdown文件的完整路径:

import subprocess
fileout = os.path.splitext(filename)[0] + ".pdf"
args = ['pandoc', filename, '-o', fileout]
subprocess.Popen(args)

我也尝试了各种方法来捕获错误,但没有奏效。 然而,在控制台中,一切正常:

pandoc '[filename]' -o '[fileout]'

这不能回答您的问题(您可能特别想要/需要使用 subprocess.Popen 调用 pandoc),但有一个名为Pyandoc 的Pandoc 包装器:请参阅我的答案here

这应该可以正常工作,但您可能希望等待它完成使用subprocess.check_call而不是subprocess.Popen直接:

subprocess.check_call(args)

这也确保它成功完成。 如果状态码不为 0,则会抛出异常。

我真的不喜欢用PIPE ,它更复杂,并在Python文档subprocess建议,如果没有必要不要使用它(见第17.1.1节)。

这对我有用(取自Markx )。

文件名是不带.md的降价文件的名称,以及所需输出中的扩展名( .pdf.docx ):

def pandoc(filename, extension):
    # TODO manage pandoc errors, for example exit status 43 when citations include Snigowski et al. 2000
    options = ['pandoc', filename + '.md', '-o', filename + extension]
    options += ['--ascii', '-s', '--toc'] # some extra options
    options += ['--variable=geometry:' + 'a4paper'] # to override the default letter size
    print(options)  # for debugging
    return subprocess.check_call(options)

如果出现问题,则引发异常。 如果您想获取状态代码而不是异常,我认为您应该将check_call替换为call ,但请参阅docs

如果您想使用引文,请使用bibliography选项查看Markx项目中我的原始实现。

如果要捕获 Popen 调用产生的 stdout 和 stderr,则需要将 PIPE 与communication() 结合使用。

from subprocess import Popen, PIPE

fileout = os.path.splitext(filename)[0] + ".pdf"
args = ['pandoc', filename, '-o', fileout]
stdout, stderr = Popen(args, stdout=PIPE, stderr=PIPE).communicate()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM