
[英]Why doesn't Python check_output() return when calling daemon?
[英]python check_output prints but doesn't store in var
我通常使用非常简单的subprocess.check_output
:
process = subprocess.check_output("ps aux", shell=True)
print process #display the list of process
如果我担心stderr
有某些东西,可以这样使用:
process = subprocess.check_output("ps aux 2> /dev/null", shell=True)
print process #display the list of process
但是我对nginx -V
有问题:
modules = subprocess.check_output("nginx -V", shell=True) #display the result
print modules #empty
modules = subprocess.check_output("nginx -V 2> /dev/null", shell=True) #display nothing
print modules #empty
为什么命令nginx -V
行为方式不同(全部在stderr
打印)? 我该如何使用subprocess.check_output`来设计变通方法?
将标准错误重定向到Shell中的标准输出的方式是2>&1
但您最好避免在这里完全使用Shell。
p = subprocess.Popen(['nginx', '-V'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if out == '':
modules = err
modules = out
如果您使用的是较新的Python,还可以考虑切换到subprocess.run()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.