如果我喜欢:
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/