问题描述
我使用子进程在Python脚本中调用外部程序。外部程序产生了大量的输出。我需要捕获该程序的输出。当前代码如下所示:
process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
process.stdin.write('gams "indus89.gms"
')
while process.poll() != None:
line = process.stdout.readline()
print line
我在此代码中收到的错误是
进程试图写入不存在的管道。
如果我使用以下代码:
process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
process.stdin.write('gams "indus89.gms"
')
o, e = process.communicate()
print o
则不捕获程序的输出。
我应该如何更改代码,以便可以在第三方程序运行时捕获其输出?
推荐答案
打开有点矫枉过正。
尝试:
output = subprocess.check_output('gams "indus89.gms"
', shell=True)
希望这能在您的环境中发挥作用。