【问题标题】:Python subprocess call to xpdf's pdftotext not working with encoding对 xpdf 的 pdftotext 的 Python 子进程调用不适用于编码
【发布时间】:2017-07-28 08:30:56
【问题描述】:

我正在尝试使用 python subprocess 模块运行 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

当我从 cmd 中删除最后一个参数“-enc UTF-8”时,它在 python 中工作正常。

当我在cmd 中运行pdftotext pdf txt -enc UTF-8 时,它工作正常。

我错过了什么?

谢谢。

【问题讨论】:

  • 相信你需要[pdftotext, pdf, txt, '-enc', 'UTF-8']
  • 我试过了,但它可以工作,但编码不起作用。它给出了 ANSI 编码的文件。
  • 我明白了....将命令作为字符串传递?
  • 我将所有内容都移到了单个文件夹中,然后cmd = r"pdftotext file.pdf demo.txt -enc UTF-8" 完美运行。所以问题在于cmd 格式。

标签: python python-3.x subprocess pdftotext


【解决方案1】:

subprocess 有一些处理命令的复杂规则。来自docs:

shell 参数(默认为 False)指定是否使用 shell 作为要执行的程序。如果 shell 为 True,则为 建议将 args 作为字符串而不是序列传递。

此答案here中解释了更多详细信息。

因此,正如文档所解释的,您应该将命令转换为字符串:

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

现在,拨打subprocess:

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

【讨论】:

  • 我试过cmd = r"""{} "{}" "{}" -enc UTF-8""".format(pdftotext, pdf, txt),因为我的路径中有空格并且文件是动态生成的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 2019-04-17
  • 2018-03-09
  • 1970-01-01
  • 2021-06-24
  • 1970-01-01
相关资源
最近更新 更多