对包含subprocess.call()的Python脚本的Python输出进行capturing时出现问题

2024-09-30 20:33:52 发布

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

这是我的问题。尝试捕获Python输出时,subprocess.call()输出错误地出现在print()输出之前。我在windows10上使用python3.7.2从命令窗口运行Python

下面是一个小例子来说明这个问题:

import subprocess

print("test")
subprocess.call("where python",shell=True)

请注意,print()输出应该在subprocess.call()输出之前

以下是在不捕获输出的情况下运行时得到的结果:

c:\Users\GeoffAlexander\Documents\Python>python test.py
test
C:\Users\GeoffAlexander\AppData\Local\Programs\Python\Python37-32\python.exe>
c:\Users\GeoffAlexander\Documents\Python>

print()输出正确地位于subprocess.call()输出之前

但是,当我将输出重定向到文件时,得到的结果如下:

c:\Users\GeoffAlexander\Documents\Python>python test.py > test.out

c:\Users\GeoffAlexander\Documents\Python>cat test.out
C:\Users\GeoffAlexander\AppData\Local\Programs\Python\Python37-32\python.exe
test

c:\Users\GeoffAlexander\Documents\Python>

请注意,subprocess.call()输出错误地出现在print()输出之前

为什么会这样?如何以正确的顺序捕获Python输出


Tags: pytestlocal错误calloutexeusers
2条回答

您需要通过管道与子流程通信

参见https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python以获取示例

How can I capture the Python output in the correct order?

你好

在打印调用之后,请尝试刷新标准输出,例如:

import subprocess
import sys

print("test")
sys.stdout.flush()
subprocess.call("echo python",shell=True)

输出正确(在Linux系统上测试):

$ python test.py
test
python
$ python test.py > filename
$ cat filename
test
python

相关问题 更多 >