2012-09-29 48 views
2

我有问题,使用subprocess.Popen从python调用pandoc。它全部在控制台中工作。这是代码。现在使用subprocess从python调用pandoc。打开

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

我的Python代码使用filename是完整路径我的降价文件:

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

我也尝试过各种方法来捕捉一个错误,但没有奏效。在控制台中,然而,一切都很好运行:

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

回答

3

这应该工作得很好,但你可能要等待它使用subprocess.check_call而直接比subprocess.Popen完成:

subprocess.check_call(args) 

这也确保它成功完成。如果状态码不是0,则会引发异常。

1

如果您想捕获Popen调用产生的stdout和stderr,则需要将PIPE与communicate()一起使用。

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() 
5

这不回答你的问题(你可以特别想/需要使用subprocess.Popen调用pandoc),但有一个Python包装的Pandoc称为Pyandoc:看我的回答here

1

我真的不喜欢使用PIPE,它更复杂,subprocess上的Python文档建议在不需要时不要使用它(请参阅section 17.1.1)。

这适用于我(取自Markx)。

Filename是降价文件,而不在.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) 

如果有一个问题例外中提出。如果您想获取状态代码而不是例外情况,我认为您应该用call替换check_call,但请参阅docs

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