2012-09-29 45 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項目中查看我的原始實施。