Python 中 subprocess.PIPE 的非阻塞读取 - A non-blocking read on a subprocess.PIPE in Python

问题:

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章