Created
June 27, 2014 13:47
-
-
Save alfredodeza/82b0716b8898c3a0e2b1 to your computer and use it in GitHub Desktop.
alternating stderr with stdout with subprocess.Popen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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