fcntl,
select,
asyncproc不会在这种情况下帮助。
不管使用什么操作系统,一种可靠地读取流而不阻塞的可靠方法是使用
Queue.get_nowait():
import sysfrom subprocess import PIPE, Popenfrom threading import Threadtry: from queue import Queue, Emptyexcept importError: from Queue import Queue, Empty # python 2.xON_POSIX = 'posix' in sys.builtin_module_namesdef 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 programt.start()# ... do other things here# read line without blockingtry: line = q.get_nowait() # or q.get(timeout=.1)except Empty: print('no output yet')else: # got line # ... do something with line


