繁体   English   中英

从包含 subprocess.call() 的 Python 脚本捕获 Python 输出的问题

[英]Problem with capaturing Python output from a Python script containing subprocess.call()

这是我的问题。 尝试捕获 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 输出?

你好,

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

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

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

有关示例,请参见https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM