【问题标题】:CalledProcessError: Command '['pdftotext', '-layout', 'coburns.pdf', '-']' returned non-zero exit status 1?CalledProcessError:命令'['pdftotext','-layout','coburns.pdf','-']'返回非零退出状态1?
【发布时间】:2020-05-02 14:58:17
【问题描述】:

我在运行这部分代码时不断收到错误消息。我已经尝试按照subprocess.check_output 文档的建议实施universal_newlines=True,但我得到了同样的错误。为什么会发生这种情况,我可以做些什么来解决它?

for filename in os.listdir(directory):
    if filename in new_list:
        pdf = filename
        output = subprocess.check_output(['pdftotext', '-layout', pdf, '-'], universal_newlines=True).decode()
        pages = output.strip('\f').split('\f')
        page = pages[-1]

错误信息:

---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
<ipython-input-153-adc4a58d7f21> in <module>
      9     if filename in new_list:
     10         pdf = filename
---> 11         output = subprocess.check_output(['pdftotext', '-layout', pdf, '-'], universal_newlines=True).decode()
     12         pages = output.strip('\f').split('\f')
     13         page = pages[-1]

/usr/lib/python3.8/subprocess.py in check_output(timeout, *popenargs, **kwargs)
    409         kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b''
    410 
--> 411     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
    412                **kwargs).stdout
    413 

/usr/lib/python3.8/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    510         retcode = process.poll()
    511         if check and retcode:
--> 512             raise CalledProcessError(retcode, process.args,
    513                                      output=stdout, stderr=stderr)
    514     return CompletedProcess(process.args, retcode, stdout, stderr)

CalledProcessError: Command '['pdftotext', '-layout', 'coburns.pdf', '-']' returned non-zero exit status 1.

【问题讨论】:

  • check_ouput 意味着如果进程中的错误代码不为零,则引发CalledProcessError。这里声明它是1。因此,您应该调查为什么pdftotext 产生1 而不是0
  • pdftotext 声明 1 表示打开 PDF 时出错。但是,如果我将 pdf 部分从 for 循环和条件中取出,则没有问题。您认为问题是由循环本身引起的吗?
  • 您很可能试图打开不是有效 pdf 或不在 pdftotext 查找位置的内容。尝试在循环中打印您的filenames 并检查路径是否正确。
  • filename 打印出正确的文件名。它应该打印文件的整个路径吗?
  • 它应该打印允许pdftotext 找到它的内容:您是否从同一目录启动它?

标签: python error-handling subprocess pdftotext python-re


【解决方案1】:

如 cmets 中所述,check_output 实际上是在进程返回的代码不是0 时引发CalledProcessError

这里这段代码是1,表示pdftotext无法打开pdf,要么不正确,要么找不到。

您正在使用os.listdir,它产生的文件名与directory 参数相关,这不一定与check_output 默认启动pdftotext 的当前工作目录相同。

我可以看到三个解决方案:

【讨论】:

  • 谢谢!我将pdf = filename 更改为pdf = os.path.join(directory, filename),现在它完美运行!
猜你喜欢
  • 2021-01-11
  • 1970-01-01
  • 2019-10-02
  • 2019-02-09
  • 1970-01-01
  • 2019-08-12
  • 2021-02-15
  • 1970-01-01
  • 2014-04-09
相关资源
最近更新 更多