捕获 python 子进程的输出

Catch output from python subprocess

我正在尝试捕获通过 python 脚本执行的命令的输出。 我知道有很多关于如何执行此操作的示例,但我无法找到解决方案。

示例:

这个例子有效:

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

结果:

houhou@box:~/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)

结果:

houhou@box:~/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:

我不知道如何捕捉这个输出。看起来在 python 可以读取之前打印出表明 nginx 配置正常的消息。 任何帮助将不胜感激。

干杯。

'zondo' 在评论中正确预测,'nginx' 将以上消息发送到 stderr,您也可以修改代码以读取该消息 -

>>> 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