gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:08 25 4
gpt4 key购买 nike

如果我喜欢:

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 并调用 communicate 就可以了;只需使用 check_output:

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com