简体   繁体   English

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

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

Here's my problem.这是我的问题。 When attempting to capture Python output, subprocess.call() output incorrectly comes before print() output.尝试捕获 Python 输出时, subprocess.call() 输出错误地出现在 print() 输出之前。 I'm running Python from a command window using Python 3.7.2 on Windows 10.我在 Windows 10 上使用 Python 3.7.2 从命令窗口运行 Python。

Here's a small example illustrating the problem:这是一个说明问题的小例子:

import subprocess

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

Note that the print() output should come before the subprocess.call() output.请注意,print() 输出应该在 subprocess.call() 输出之前。

Here's what I get when I run without capturing output:这是我在不捕获输出的情况下运行时得到的结果:

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>

The print() output correctly comes before the subprocess.call() output as expected. print() 输出按预期正确出现在 subprocess.call() 输出之前。

However when I redirect the output to a file, here's what I get:但是,当我将输出重定向到文件时,我得到的是:

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>

Note that the subprocess.call() output incorrectly comes before the print() output.请注意, subprocess.call() 输出错误地出现在 print() 输出之前。

Why does this happen?为什么会发生这种情况? How can I capture the Python output in the correct order?如何以正确的顺序捕获 Python 输出?

How can I capture the Python output in the correct order?如何以正确的顺序捕获 Python 输出?

Hello,你好,

Well try flushing your standard output after your print call, like:好吧,尝试在打印调用后刷新标准输出,例如:

import subprocess
import sys

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

The output will be correct (tested on Linux system):输出将是正确的(在 Linux 系统上测试):

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

You need to communicate with the subprocess via a pipe您需要通过管道与子进程通信

See https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python for an example有关示例,请参见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