在Linux上针对此问题的两种解决方案:
第一个是使用文件将输出写入其中,并同时读取输出:
from subprocess import Popen, PIPEfw = open("tmpout", "wb")fr = open("tmpout", "r")p = Popen("./a.out", stdin = PIPE, stdout = fw, stderr = fw, bufsize = 1)p.stdin.write("1n")out = fr.read()p.stdin.write("5n")out = fr.read()fw.close()fr.close()
第二,正如JF Sebastian提供的那样,是使用fnctl模块使p.stdout和p.stderr管道不阻塞:
import osimport fcntlfrom subprocess import Popen, PIPE def setNonBlocking(fd): """ Set the file description of the given file descriptor to non-blocking. """ flags = fcntl.fcntl(fd, fcntl.F_GETFL) flags = flags | os.O_NonBLOCK fcntl.fcntl(fd, fcntl.F_SETFL, flags)p = Popen("./a.out", stdin = PIPE, stdout = PIPE, stderr = PIPE, bufsize = 1)setNonBlocking(p.stdout)setNonBlocking(p.stderr)p.stdin.write("1n")while True: try: out1 = p.stdout.read() except IOError: continue else: breakout1 = p.stdout.read()p.stdin.write("5n")while True: try: out2 = p.stdout.read() except IOError: continue else: break
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)