2017-02-17 20 views
0

不存储我通常使用非常简单subprocess.check_output蟒蛇check_output版画但在VAR

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)?我如何设计esealy与``subprocess.check_output`解决方法?

+0

这可能是流程具体打印到它运行,而不是正常渠道的终端。 – languitar

回答

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

+0

另请参阅http://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess/36008455#36008455了解为什么要避免'shell = True'的一般讨论。 – tripleee