2017-07-28 70 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好吧,编辑:) –

相关问题