具有超时的非阻塞I / O.

时间:2014-12-22 13:11:59

标签: python io

我试图以非阻塞模式读取管道。这是一个类似的问题和答案,但它使用线程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是生成输出的原因

#!/bin/bash

for i in `seq 1 400`;
do
    sleep 1;
    # doesn't have newlines
    echo -n $i
done

1 个答案:

答案 0 :(得分:1)

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),