2

Example test file (print.py):

import sys
print('stdout')
print('stderr', file=sys.stderr)

Code for running it (x.py):

import subprocess
cmd = ['python', 'print.py']
print(subprocess.check_output(cmd, universal_newlines=True, stderr=subprocess.STDOUT))

If I run print.py from the shell, it prints stdout first. However, If I run x.py, it prints stderr first. Is there any way for me to get the output in the correct order?

jck
  • 1,910
  • 4
  • 18
  • 25
  • Note: in general, if stdout and stderr are not merged; the order can't be preserved (it may be undefined) even if stdout/stderr are unbuffered. Related: [Run command and get its stdout, stderr separately in near real time like in a terminal](http://stackoverflow.com/a/31953436/4279) – jfs Mar 16 '16 at 00:16

1 Answers1

6

Your code is buffering (i.e. delaying) its output. The details of the buffer process vary according to whether the output is the console or a pipe.

Try this:

cmd = ['python', '-u', 'print.py']

Reference: https://docs.python.org/3.5/using/cmdline.html#cmdoption-u

Robᵩ
  • 163,533
  • 20
  • 239
  • 308