2012-05-22 33 views
3

我使用子进程在Python脚本内调用外部程序。外部程序产生大量输出。我需要捕获这个程序的输出。当前的代码是这样的:使用通信通过子进程捕获输出无w/o

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 

我与此代码得到的错误是

过程试图写入到不存在的管道。

如果我使用以下代码:

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 

然后该程序的输出不捕获。

我应该如何更改我的代码,以便在运行时捕获第三方程序的输出?

+2

为什么你使用'cmd.exe'和'shell = False',为什么不'''gams“indus89.gms”'''shell = True'? –

回答

3

Popen是矫枉过正。

尝试:

output = subprocess.check_output('gams "indus89.gms"\r\n', shell=True) 

希望这将在您的环境中工作。

+0

我尝试过,但仍无法捕捉到需要捕捉的输出。 –

+0

@AdityaGore是什么被命令返回? – jtmoulia

+0

对不起,我正在运行旧代码。现在一切正常。谢谢你的帮助.. –