开发者

Python subprocess produced output or not

This question is in relation to:

python, subprocess: reading output from subprocess

If P is a subprocess started with a command along the lines of

import subprocess

P = subprocess.Popen ("command", stdout=subprocess.PIPE)

we can read the outpu开发者_JAVA百科t P produces by P.stdout.readline (). This is a blocking read though. How can I check if there is output ready for reading (without blocking)?


If you are using *nix, then you can use the select module to poll the stdout file descriptor

import subprocess
import select
poller = select.epoll()

P = subprocess.Popen ("command", stdout=subprocess.PIPE)
poller.register(P.stdout, select.EPOLLHUP)

while True:
    #block indefinitely: timeout = -1
    #return immediately: timeout = 0
    for fd, flags in poller.poll(timeout=0)
        foo = P.stdout.readline()
    #do something else before the next poll
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜