2017-07-28 67 views
0

我試圖運行pdftotext使用python subprocess模塊。Python子進程調用xpdf的pdftotext不能與編碼一起工作

import subprocess 

pdf = r"path\to\file.pdf" 
txt = r"path\to\out.txt" 
pdftotext = r"path\to\pdftotext.exe" 

cmd = [pdftotext, pdf, txt, '-enc UTF-8'] 
response = subprocess.check_output(cmd, 
       shell=True, 
       stderr=subprocess.STDOUT) 

TB

CalledProcessError: Command '['path\\to\\pdftotext.exe', 
'path\\to\\file.pdf', 'path\\to\\out.txt', '-enc UTF-8']' 
returned non-zero exit status 99 

當我刪除最後一個參數 '-enc UTF-8' 從CMD,它在Python的工作原理確定。

當我運行pdftotext pdf txt -enc UTF-8cmd,它工作正常。

我缺少什麼?

謝謝。

+0

我相信你需要'[pdftotext,PDF,TXT ,'-enc','UTF-8']' –

+0

我試過了,但它工作但編碼不起作用。它給ANSI編碼的文件。 – Rahul

+0

我看到了....將命令作爲字符串傳遞? –

回答

1

subprocess對處理命令有一些複雜的規則。從docs

殼參數(默認爲假)指定是否使用 殼作爲要執行的程序。如果shell爲True,建議將作爲字符串傳遞,而不是作爲序列傳遞。

此答案中解釋更多詳細內容here

因此,隨着文檔說明,你應該將命令轉換爲字符串:

cmd = r"""{} "{}" "{}" -enc UTF-8""".format('pdftotext', pdf, txt) 

現在,撥打subprocess爲:

subprocess.call(cmd, shell=True, stderr=subprocess.STDOUT) 
+0

我試過'cmd = r「」「{}」{}「」{}「-enc UTF-8」「」.format(pdftotext,pdf,txt)',因爲我的路徑中有空格,動態。 – Rahul

+0

@Rahul好吧,編輯:) –

相關問題