这是我的问题。尝试捕获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输出
您需要通过管道与子流程通信
参见https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python以获取示例
你好
在打印调用之后,请尝试刷新标准输出,例如:
输出正确(在Linux系统上测试):
相关问题 更多 >
编程相关推荐