Getting stdout and stderr from subprocess in correct order

Ivan "Rambius" Ivanov rambiusparkisanius at gmail.com
Fri Mar 3 23:16:59 EST 2017


Dear colleagues,

I using subprocess module and I am wondering how I can get the output
of the spawned process's stdout and stderr in the right order. Here
are my sample programs:

$ cat subprc.py
import subprocess
import sys

f = 'hw.py'
p = subprocess.run([sys.executable, f], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
print(p.stdout)
print(p.stderr)

$ cat hw.py
import sys

print("a", file=sys.stdout)
print("b", file=sys.stderr)
print("c", file=sys.stdout)
print("d", file=sys.stderr)

When i run hw.py I get

$ ./hw.py
a
b
c
d

When I run it through subprc.py, I do get standard out and standard
errors streams, but they are separated and not in the order above:

$ ./subprc.py
b'a\nc\n'
b'b\nd\n'

How should I use subprocess in order to get the outputs in the correct
order? Thank you for your help in advance.

Regards
Rambius

-- 
Tangra Mega Rock: http://www.radiotangra.com


More information about the Python-list mailing list