【问题标题】:Subprocess command throwing error while converting docx to pdf将 docx 转换为 pdf 时子进程命令抛出错误
【发布时间】:2021-11-26 10:05:26
【问题描述】:

我正在使用 python 的子进程模块在我的 windows 机器上运行以下代码。

import subprocess

args = ["abiword --to=pdf '{}'".format('test.docx')]
process = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, timeout=None)
print(process.stdout.decode())
filename = re.search('-> (.*?) using filter', process.stdout.decode())
print(filename.group(1))

但是subprocess.run 给出以下错误:

b'\'"abiword --to=pdf \'test.docx\'"\' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n'

如何解决此错误,我现在应该如何处理? 另外,在我的 Windows 机器上使用 abiword 命令是否正确?我想在不安装任何第三方软件(如 libreoffice)的情况下将我的 docx 转换为 pdf。

【问题讨论】:

  • 您的机器上是否安装了abiword,它在PATH 中是否可用?换句话说,如果您在控制台 CMD.exe 窗口中键入 abiword --to-pdf test.docx 会发生什么?
  • 是的,我已经在我的 win 机器上安装了 abiword,并且 Path 变量已更新为 .exe 文件路径“C:\Program Files (x86)\AbiWord\bin”。我在 cmd 上执行 abiword --to-pdf test.docx 时没有看到任何错误,但我没有看到任何 pdf 被创建。
  • @k-j 现在是 2.9.4
  • 我安装了 2.8.4,但也没有用。命令行不会生成任何 pdf。我使用了 Libreoffice,但这并不能保持表格和图像的对齐。不知道我应该使用什么其他模块。

标签: python python-3.x python-docx doc


【解决方案1】:

这里有 2 个不同的问题。

第一个很容易解决:您没有为子进程提供正确的参数。第一个参数 (args) 可以是包含完整命令行的字符串,也可以是包含命令和参数作为单独元素的列表。所以你应该使用:

args = "abiword --to=pdf '{}'".format('test.docx')

(一个简单的字符串,而不是一个列表)或:

args = ["abiword", "--to=pdf",  '{}'.format('test.docx')]

第二个是直到您可以通过在控制台 CMD.exe 窗口中输入 abiword --to-pdf 命令生成 pdf 之前,使用 subprocess.run 启动的相同命令不会产生更好的结果...

【讨论】:

  • '{}'.format('test.docx') 只是写'test.docx'的一种邪恶的复杂方式
  • @tripleee:你说得对,但我不想更改那部分,因为它与 OP 问题完全无关。
  • 在 Windows 上,shell=True 与否之间的差异较小,但为了记录,使用第二种形式的唯一 portable 方法是同时删除 @987654329 @。或许也可以看看Actual meaning of shell=True in subprocess
  • 如果abiword 因某种原因失败,可能还会添加check=True 以使Python 引发异常。
  • @serge-ballesta 该命令没有抛出任何错误,但也没有生成 PDF。我尝试了另一种使用 Libreoffice 将 docx 转换为 pdf 的方法,它奏效了。
【解决方案2】:

使用 abiword 的完整路径:/usr/bin/abiword

【讨论】:

  • 如果他们尝试执行的命令实际上是abiword,那将有所帮助,但根据错误消息,它不是。
猜你喜欢
  • 2019-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多