Created
March 22, 2012 11:45
-
-
Save maxp/2157865 to your computer and use it in GitHub Desktop.
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 sys | |
| from subprocess import PIPE, Popen | |
| from threading import Thread | |
| try: | |
| from Queue import Queue, Empty | |
| except ImportError: | |
| from queue import Queue, Empty # python 3.x | |
| ON_POSIX = 'posix' in sys.builtin_module_names | |
| def enqueue_output(out, queue): | |
| for line in iter(out.readline, b''): | |
| queue.put(line) | |
| out.close() | |
| p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX) | |
| q = Queue() | |
| t = Thread(target=enqueue_output, args=(p.stdout, q)) | |
| t.daemon = True # thread dies with the program | |
| t.start() | |
| # ... do other things here | |
| # read line without blocking | |
| try: line = q.get_nowait() # or q.get(timeout=.1) | |
| except Empty: | |
| print('no output yet') | |
| else: # got line | |
| # ... do something with line |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment