带timeou的非阻塞I/O

2024-06-07 19:04:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在非阻塞模式下读取管道。这里有一个类似的问题和答案,但它使用线程Non-blocking read on a subprocess.PIPE in python

我尝试了下面的方法,看起来比使用线程更简单,但是只有在输出是行缓冲的情况下才是非阻塞的-不确定我是否做错了,所以有人能给我指出正确的方向吗?在

#!/usr/bin/python

import select
from subprocess import *
import time

# do non-blocking read but timeout after some time as we don't want to poll forever   
timeout = 4
READ_ONLY = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR

poller = select.poll()
proc = Popen("./output.sh".split(), stdout=PIPE);
poller.register(proc.stdout, READ_ONLY)

now = time.time()
end = now + timeout

while time.time() < end:
    if poller.poll(timeout):
        # works as expected as long as output.sh produces lines
        # read() also blocks
        print "%s" % proc.stdout.readline(),

proc.kill()

output.sh是生成输出的内容

^{pr2}$

Tags: importreadoutputtimeasshstdouttimeout
1条回答
网友
1楼 · 发布于 2024-06-07 19:04:04

poll()函数表示至少有一个字节可以读取。如果您调用readline(),那么您将等待一个完整的行被读取。您需要改为使用read(1)。在

while time.time() < end:
    if poller.poll(timeout):
        # works as expected as long as output.sh produces lines
        # read() also blocks
        print "%s" % proc.stdout.read(1),

相关问题 更多 >

    热门问题