[英]Non-blocking I/O with timeout
我正在尝试以非阻塞模式读取管道。 这是一个类似的问答,但它使用线程在子进程上非阻塞读取。
我尝试了以下操作,看起来比使用线程更简单,但仅在输出是行缓冲的情况下才是非阻塞的-不知道我是否做错了,所以有人可以指出正确的方向吗?
#!/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
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),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.