Created
April 15, 2016 00:41
-
-
Save nicelifeBS/4eaf13d2d0c4e10285b46737e8d2d1f2 to your computer and use it in GitHub Desktop.
Run a subprocess and output stdout in a non-blocking fasion
This file contains hidden or 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 threading | |
def _print_stdout(process): | |
''' | |
Print out the stream line by line. If line is empty we know that the process has finished and we exit | |
''' | |
while True: | |
try: | |
line = process.stdout.readline() | |
except: | |
break | |
else: | |
if line: | |
print line.strip() | |
else: | |
break | |
def run(cmd): | |
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) # redirecting stderr is optional | |
# we create a separate process for printing to prevent blocking | |
thread = threading.Thread(target=_print_stdout, args=[process]) | |
thread.daemon = True | |
thread.start() | |
process.wait() | |
if __name__ == '__main__': | |
cmd = ['ls', '-l'] | |
run(cmd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment