【问题标题】:python check_output prints but doesn't store in varpython check_output 打印但不存储在 var
【发布时间】:2017-02-17 09:40:17
【问题描述】:

我通常用很简单的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` 设计一个解决方法?

【问题讨论】:

  • 可能是某个进程专门打印到运行它的终端而不是正常通道。

标签: python nginx subprocess stderr


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 2014-08-29
相关资源
最近更新 更多