问题:
I'm using the subprocess module to start a subprocess and connect to its output stream (standard output).我正在使用subprocess 模块来启动一个子进程并连接到它的输出流(标准输出)。 I want to be able to execute non-blocking reads on its standard output.我希望能够对其标准输出执行非阻塞读取。 Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke .readline
?有没有办法使 .readline 非阻塞或在调用.readline
之前检查流上是否有数据? I'd like this to be portable or at least work under Windows and Linux.我希望它是可移植的,或者至少可以在 Windows 和 Linux 下工作。
Here is how I do it for now (it's blocking on the .readline
if no data is available):这是我现在的.readline
如果没有数据可用,它会在.readline
上阻塞):
p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
解决方案:
参考一: https://en.stackoom.com/question/1ZfH参考二: https://stackoom.com/question/1ZfH