【问题标题】:Cannot run '>' for a terminal command in python无法在 python 中为终端命令运行“>”
【发布时间】:2020-07-28 08:54:10
【问题描述】:

感谢您帮助我。

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

我做错了什么?

【问题讨论】:

    标签: python python-3.x doc


    【解决方案1】:

    > 字符被 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 中捕获了写入该流的任何内容。

    【讨论】:

    • 它有效,只是想知道我如何知道通信的哪个索引值包含什么,任何文档或类似的东西
    • @Anil:从subprocess module documentation,“communicate() 返回一个元组(stdout_data, stderr_data)”。
    猜你喜欢
    • 2022-11-17
    • 2016-08-24
    • 2013-09-18
    • 1970-01-01
    • 2018-12-28
    • 2015-10-19
    • 2022-01-22
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多