gpt4 book ai didi

python - 无法在 python 中为终端命令运行 '>'

转载 作者:行者123 更新时间:2023-12-04 09:18:57 25 4
gpt4 key购买 nike

谢谢你的协助。
我正在尝试从 python 运行 antiword 以将 .docx 转换为 .doc。我已将子流程用于该任务。

import subprocess
test = subprocess.Popen(["antiword","/home/mypath/document.doc",">","/home/mypath/document.docx"], stdout=subprocess.PIPE)
output = test.communicate()[0]

但它返回错误,
I can't open '>' for reading
I can't open '/home/mypath/document.docx' for reading

但是相同的命令在终端中有效
antiword /home/mypath/document.doc > /home/mypath/document.docx
我究竟做错了什么 ?

最佳答案

>字符被 shell 程序解释为输出流重定向。然而,subprocess不使用shell,所以没有什么可以解释>字符作为重定向。因此 >字符将传递给命令。毕竟,它是一个完全合法的文件名:subprocess 怎么样?应该知道您实际上没有名为 > 的文件?
不清楚您为何尝试重定向 antiword 的输出到文件并读取变量 output 中的输出.如果它被重定向到一个文件,那么在 output 中将没有任何内容可以读取。 .
如果你想重定向 subprocess 的输出调用一个文件,用Python打开该文件进行写入并将打开的文件传递给subprocess.Popen :

with open("/home/mypath/document.docx", "wb") as outfile:
test = subprocess.Popen(["antiword","/home/mypath/document.doc"], stdout=outfile, stderr=subprocess.PIPE)
error = test.communicate()[1]
进程可能会写入其标准错误流,因此我在变量 error 中捕获了写入该流的任何内容。 .

关于python - 无法在 python 中为终端命令运行 '>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63130424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com