python check_output打印但不存储在var

时间:2017-02-17 09:40:17

标签: python nginx subprocess stderr

我通常只使用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`设计esealy解决方法?

1 个答案:

答案 0 :(得分:0)

将标准错误重定向到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()