2016-02-28 129 views
1

我试图从通过python脚本执行的命令捕获输出。 我知道有很多关于如何做到这一点的例子,但我无法获得解决方案。从python子进程捕获输出

例子:

本例使用:

#!/usr/bin/python 
import subprocess 
process = subprocess.Popen(['whoami'], stdout=subprocess.PIPE) 
stdout = process.communicate()[0] 
print 'STDOUT:{}'.format(stdout) 

结果:

[email protected]:~/Documents$ python example.py 
STDOUT:houhou 

这不起作用:

我需要运行以下命令: 'nginx的-t'

import subprocess 
process = subprocess.Popen(['nginx', '-t'], stdout=subprocess.PIPE) 
stdout = process.communicate()[0] 
print 'STDOUT:{}'.format(stdout) 

结果:

[email protected]:~/Documents$ python example.py 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 
nginx: configuration file /etc/nginx/nginx.conf test is successful 
STDOUT: 

我不知道如何抓住这个输出。看起来这个消息表明nginx配置是好的,在python可以读取它之前打印出来。 任何帮助,将不胜感激。

干杯。

+1

是它可能被打印成'stderr'? – zondo

回答

2

“zondo”正确的评论,“nginx的”预测发送上述消息到标准,您可以修改代码以读取消息too-

>>> process = subprocess.Popen(['nginx', '-t'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
>>> out,err = process.communicate() 
>>> print out 

>>> print err 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 
nginx: configuration file /etc/nginx/nginx.conf test is successful 
+0

你可以使用'output = check_output('nginx -t'.split(),stderr = STDOUT)' – jfs

+0

谢谢!解决方案就像AlokThakur和Zondo用'stderr'说的,我之前用'stderr'尝试过,但我以错误的方式做了... – chrigu

+0

@chrigu您可能想接受此答案,以便其他用户也将受益。 – AlokThakur