【问题标题】:Capture output of Popen when shell=True当 shell=True 时捕获 Popen 的输出
【发布时间】:2014-07-23 10:31:02
【问题描述】:

命令提示符:

C:\Users\Documents\libexe\tfc\bin\Debug>asc-dir
asc-dir.: directory not linked to an ASC directory //Expected output

测试脚本:

proc = subprocess.Popen('asc-dir', stdout=subprocess.PIPE, shell = True)
(result, err) = proc.communicate()

这会将“asc-dir.: directory not linked to an ASC directory”打印到控制台,但不会保存到resulterr

如何将输出保存到 result / err?

当我尝试 Popenshell=False 时,我收到以下错误:

Error:
    WindowsError: [Error 2] The system cannot find the file specified
    Press any key to continue . . .

【问题讨论】:

  • >您需要在 Windows 上指定 shell=True 的唯一情况是当您希望执行的命令内置于 shell 中时(例如 dircopy)您真的需要吗?
  • 正如我所说,当 shell=False 时,我在问题的底部得到错误。
  • @Jahaja:shell=True and shell=False differ in how the executable is found on Windows。对于shell=False,OP 可能需要明确提供扩展,例如'asc-dir.cmd'

标签: python shell popen


【解决方案1】:

stderr=subprocess.PIPE 添加到Popen。否则,标准错误将继续转到子进程从您的脚本继承的任何文件。

【讨论】:

    【解决方案2】:

    删除shell=True,除非你真的需要它。听起来真正的问题是 Windows 找不到 asc-dir 可执行文件。它安装/位于哪里?该目录是否在 PATH 环境变量中?如果没有,您可以添加它,或者在调用 Popen 时指定可执行文件的完整路径,例如

    proc = subprocess.Popen(r'C:\program files\asc\bin\asc-dir', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    

    【讨论】:

    • 这给了我以下错误WindowsError: [Error 193] %1 is not a valid Win32 application
    • 啊,所以 asc-dir 不是编译后的可执行文件,它是脚本还是什么?在这种情况下,使用 shell=True 运行它可能没问题,我的 Windows-fu 很弱;-)
    • 是的,它是一个批处理文件,抱歉 - 首先应该提到这一点
    • @Tomcelic:您是否尝试过提供全名(带扩展名),例如'asc-dir.exe' 如果shell=False?注意:我不认为,如果带有shell=True 的命令设法找到asc-dir 程序,您需要提供完整路径。
    • @TomDalton:除非您使用相应的管道读/写,否则不要使用subprocess.PIPE
    猜你喜欢
    • 2013-02-20
    • 2015-09-21
    • 1970-01-01
    • 2013-05-20
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    相关资源
    最近更新 更多