【发布时间】:2019-02-20 08:24:00
【问题描述】:
这是我的问题。尝试捕获 Python 输出时,subprocess.call() 输出错误地出现在 print() 输出之前。我在 Windows 10 上使用 Python 3.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 输出?
【问题讨论】:
标签: python