
使用来使管道成为非阻塞状态
fcntl.fcntl,并使用
select.select来等待数据在任一管道中变为可用。例如:
# Helper function to add the O_NonBLOCK flag to a file descriptordef make_async(fd): fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)# Helper function to read some data from a file descriptor, ignoring EAGAIN errorsdef read_async(fd): try: return fd.read() except IOError, e: if e.errno != errno.EAGAIN: raise e else: return ''process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)make_async(process.stdout)make_async(process.stderr)stdout = str()stderr = str()returnCode = Nonewhile True: # Wait for data to become available select.select([process.stdout, process.stderr], [], []) # Try reading some data from each stdoutPiece = read_async(process.stdout) stderrPiece = read_async(process.stderr) if stdoutPiece: print stdoutPiece, if stderrPiece: print stderrPiece, stdout += stdoutPiece stderr += stderrPiece returnCode = process.poll() if returnCode != None: return (returnCode, stdout, stderr)
请注意,
fcntl仅在包括Cygwin的类Unix平台上可用。
如果您需要它在不使用Cygwin的Windows上运行,那是可行的,但难度要大得多。您必须:
- 使用pywin32库调用本机Win32 API
SetNamedPipeHandleState
与withPIPE_NOWAIT
一起使用以使stdout和stderr管道不阻塞- 使用
WaitForMultipleObjects
而不是select
等待数据可用 - 使用
ReadFile
读取数据
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)