我通常只使用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解决方法?
答案 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()