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

2024-05-19 07:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢你帮我

我正在尝试从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

我做错了什么


Tags: testimporthomefordoc流程opendocument
1条回答
网友
1楼 · 发布于 2024-05-19 07:22:07

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中捕获了写入该错误流的任何内容

相关问题 更多 >

    热门问题