問題:
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