我正在使用pty
读取如下进程的非阻塞stdout:
import os
import pty
import subprocess
master, slave = pty.openpty()
p = subprocess.Popen(cmd, stdout = slave)
stdout = os.fdopen(master)
while True:
if p.poll() != None:
break
print stdout.readline()
stdout.close()
除了while-loop
偶尔阻塞之外,一切都正常。这是因为print stdout.readline()
行正在等待从stdout
读取某些内容。但如果程序已经终止,我的小脚本将永远挂在那里。在
我的问题是:有没有一种方法可以窥视stdout
对象并检查是否有可供读取的数据?如果不是这样,它应该继续通过while-loop
,在那里它将发现进程实际上已经终止并中断循环。在
select.poll()答案非常简洁,但在Windows上不起作用。下面的解决方案是另一种选择。它不允许您查看stdout,但提供了readline()的非阻塞替代方法,它基于this answer:
其他非阻塞读取的解决方案已经被提出here,但对我来说并不管用:
是,使用select module's poll:
在使用期间:
^{pr2}$相关问题 更多 >
编程相关推荐