当shell = True时捕获Popen的输出

时间:2014-07-23 10:31:03

标签: python shell popen

命令提示符:

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?

当我使用Popen尝试shell=False时,出现以下错误:

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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

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