我正在尝试捕获通过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 config正常的消息。任何帮助,将不胜感激。
干杯。
'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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句