python check\u输出打印,但不存储在

2024-09-19 20:50:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我通常使用非常简单的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中打印)?我如何设计一个解决方案``子流程检查输出`? 你知道吗


Tags: ofthemodulestrueoutputcheckdisplaynginx
1条回答
网友
1楼 · 发布于 2024-09-19 20:50:16

将标准错误重定向到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,也可以考虑切换到^{}

相关问题 更多 >