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