1

Here's my problem. When attempting to capture Python output, subprocess.call() output incorrectly comes before print() output. I'm running Python from a command window using Python 3.7.2 on Windows 10.

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.

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.

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.

Why does this happen? How can I capture the Python output in the correct order?

2 Answers 2

1

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

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):

$ python test.py
test
python
$ python test.py > filename
$ cat filename
test
python
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion. It works for me on Windows as well. For completeness I suspect I should also flush stderr. This works fine for Python scripts that I wrote (or can change). But for larger scripts written by others, it can be problematic to make such changes.
0

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

1 Comment

Try to copy/paste relevant code in case the link expires

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.