how do I read everything currently in a subprocess.stdout pipe and then return?

匿名 (未验证) 提交于 2019-12-03 09:52:54

问题:

I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline.

How can I do a read of all the characters in the stdout pipe of a subprocess instance? If it matters, I'm running in Linux.

回答1:

Someone else appears to have had the same problem, you can see the related discussion here.

If you are running on Linux you can use select to wait for input on the process' stdout. Alternatively you change the mode of the process' stdout to non-blocking using

import fcntl, os  fcntl.fcntl(your_process.stdout, fcntl.F_SETFL, os.O_NONBLOCK)

after which you can loop using read() until you encounter a newline character (if you want to process the output one line at a time).



回答2:

You should loop using read() against a set number of characters.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!