Last active
August 29, 2015 14:21
-
-
Save CUXIDUMDUM/a38410ea1b23aed6431a to your computer and use it in GitHub Desktop.
non blocking thread stdout
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 threading | |
import subprocess | |
import logging | |
import os | |
import fcntl | |
logger = logging.getLogger() | |
logger.setLevel(logging.DEBUG) | |
ch = logging.StreamHandler() | |
ch.setFormatter(logging.Formatter("%(name)s - %(threadName)s - %(process)s - %(message)s")) | |
ch.setLevel(logging.DEBUG) | |
logger.addHandler(ch) | |
logger.info("hello") | |
def run(cmd): | |
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE) | |
# start a thread, set stdout async | |
thread = threading.Thread(target=log_to_worker, args=[p.stdout]) | |
thread.daemon = True | |
thread.start() | |
p.wait() #wait for proc to complete before joining thread | |
thread.join() | |
p.stdout.flush() | |
p.stdout.close() | |
p.stderr.flush() | |
p.stderr.close() | |
def log_to_worker(pipe): | |
fd = pipe.fileno() | |
data = None | |
buffer = "" | |
while True: | |
try: | |
data= os.read(fd, 512) | |
if len(data[-1]) == 0: | |
break | |
except Exception as e: | |
data = "" | |
break | |
l = data.splitlines() | |
print "first: " + l[0][0] | |
print "last: " + l[-1][-1] | |
run("cat /tmp/foo.py") | |
# http://chase-seibert.github.io/blog/2012/11/16/python-subprocess-asynchronous-read-stdout.html | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment