python - 如何在 python 中获取命令输出而不是子进程?

标签 python subprocess popen communicate

如果我喜欢:

x = subprocess.Popen(["nosetests",      
"TestStateMachine.py:FluidityTest.test_it_has_an_initial_state", "-v"], 
stdout=subprocess.PIPE)

我执行的命令的输出:

test_it_has_an_initial_state (TestStateMachine.FluidityTest) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

但是如果调用x.communicate(),例如我得到:

('', None)

例如,如何将该消息保存在变量中?

最佳答案

问题几乎可以肯定是您的命令正在写入 stderr 以及 stdout,而您只捕获 stdout。

如果要将两者合并为一个字符串,请执行以下操作:

x = subprocess.Popen(["nosetests",
                      "TestStateMachine.py:FluidityTest.test_it_has_an_initial_state", 
                      "-v"], 
                     stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

out_and_err, _ = x.communicate()

如果您想将它们作为单独的字符串获取:

x = subprocess.Popen(["nosetests",
                      "TestStateMachine.py:FluidityTest.test_it_has_an_initial_state", 
                      "-v"], 
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)

out, err = x.communicate()

这在Frequently Used Arguments下进行了解释。 :

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are… Additionally, stderr can be STDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.

但是,如果您以前从未听说过标准错误,那么您就不会去寻找这个,这是可以理解的……文档假设您了解每个程序的单独输出和错误管道的基本 C/POSIX 模型。


顺便说一句,如果您想要运行的只是运行一个程序并获取其输出,将其 stderr 与其 stdout 合并,则无需创建 Popen 并调用 在其上进行通信;只需使用check_output:

out_and_err = subprocess.check_output([… args …], stderr=subprocess.STDOUT)

关于python - 如何在 python 中获取命令输出而不是子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21127634/

相关文章:

python - 如何将 IPython 笔记本转换为 PDF 和 HTML?

python - TypeError : list indices must be integers or slices, not str - 从 json 获取

python - 我应该始终明确关闭标准输出吗?

python - STDOUT 中的子进程或 commands.getstatusoutput 并存储在变量中

python - 限制 python popen 子 snap 容器

HANDLE 的 Python ctypes

python - SQLAlchemy - 将一个类映射到两个表

python - process.communicate 和 getche() 失败

python - 在 Python 中禁用 subprocess.Popen 的控制台输出

python - Popen 等待子进程,即使直接子进程已经终止