Skip to content

Instantly share code, notes, and snippets.

@alfredodeza
Created June 27, 2014 13:47
Show Gist options
  • Save alfredodeza/82b0716b8898c3a0e2b1 to your computer and use it in GitHub Desktop.
Save alfredodeza/82b0716b8898c3a0e2b1 to your computer and use it in GitHub Desktop.
alternating stderr with stdout with subprocess.Popen
# ideally we would have output like:
$ python process.py
this is an stderr line
this is an stdout line
this is an stderr line
this is an stdout line
# but we end up having output like:
$ python process.py
this is an stdout line
this is an stdout line
this is an stderr line
this is an stderr line
import sys
sys.stderr.write('this is an stderr line\n')
sys.stdout.write('this is an stdout line\n')
sys.stderr.write('this is an stderr line\n')
sys.stdout.write('this is an stdout line\n')
import subprocess
import sys
cmd = ['python', 'mix_out.py']
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
)
if process.stdout:
while True:
out = process.stdout.readline()
if out == '' and process.poll() is not None:
break
if out != '':
print out
sys.stdout.flush()
if process.stderr:
while True:
err = process.stderr.readline()
if err == '' and process.poll() is not None:
break
if err != '':
print err
sys.stderr.flush()
returncode = process.wait()
if returncode != 0:
print "command returned non-zero exit status: %s" % returncode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment