我正在使用子进程在Python脚本中调用外部程序.外部程序产生大量输出.我需要捕获该程序的输出.当前代码是这样的:
process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
process.stdin.write('gams "indus89.gms"\r\n')
while process.poll() != None:
line = process.stdout.readline()
print line
我收到此代码的错误是
The process tried to write to a nonexistent pipe.
如果我使用以下代码:
process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
process.stdin.write('gams "indus89.gms"\r\n')
o, e = process.communicate()
print o
则不会捕获程序的输出.
我应该如何更改代码,以便在第三方程序运行时捕获其输出?
解决方法:
Popen太过分了.
尝试:
output = subprocess.check_output('gams "indus89.gms"\r\n', shell=True)
希望这将在您的环境中工作.