2013-01-14 60 views
0

我想运行一个外部程序(在这种情况下只是python -V)并捕获内存中的标准错误。如何在Python中捕获外部进程的输出

它的工作原理,如果我重定向到磁盘:

import sys, os 
import subprocess 
import tempfile 
err = tempfile.mkstemp() 
print err[1] 
p = subprocess.call([sys.executable, '-V'], stderr=err[0]) 

但是这并不有趣。然后我需要将该文件读入内存。

我想我可以创建在内存中的东西,会像使用StringIO的一个文件,但这个尝试失败:

import sys, os 
import subprocess 
import tempfile 
import StringIO 

err = StringIO.StringIO() 
p = subprocess.call([sys.executable, '-V'], stderr=err) 

我:

AttributeError: StringIO instance has no attribute 'fileno' 

PS。一旦这个工作,我也想捕获标准输出,但我想这是一样的。 ps2。我试图在Windows和Python 2.7.3

回答

2

以上您需要设置stderr = subprocess.PIPE

如:

p = subprocess.Popen(...,stderr = subprocess.PIPE) 
stdout,stderr = p.communicate() 
#p.stderr.read() could work too. 

,对于这个工作,你需要访问Popen对象,所以你不能真的在这里使用subprocess.call(你真的需要subprocess.Popen)。

+0

文档建议针对:“不要使用标准输出=管或标准错误= PIPE使用此功能。”或者是比你的建议subprocess.PIPE不同? – szabgab

+0

@szabgab - 对不起,我一定是在编辑评论时。你不能在'subprocess.call'中使用'PIPE'(或者至少你不应该)。你可以用'subprocess.Popen'来使用它,就像我在我的答案中已经证明的一样。 – mgilson

+0

事实上,我以前的评论是在只看到答案的第一行时做出的。子进程.Popen很好地工作。谢谢 – szabgab

0

使用subprocess.check_output。从docs

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) 
Run command with arguments and return its output as a byte string. 
相关问题