在没有固定缓冲区大小的情况下非阻塞地读取(os.read)FIFO

时间:2013-11-26 02:19:29

标签: python-2.7 fifo

this question中,提问者已经解决了以非阻塞方式从命名管道读取的问题,但他使用固定的缓冲区大小。有没有办法在没有固定缓冲区大小的情况下执行此操作,只是等待另一端使用换行符来终止自己的缓冲区?

1 个答案:

答案 0 :(得分:0)

假设您的分隔符为a,您可以以非阻塞方式读取多个可变长度字符串,如此程序中所示,它在从命名管道接收输出时计数。

import os
import time
import errno
import sys

io = os.open(expanduser("~/named_pipes/cob_input"), os.O_RDONLY | os.O_NONBLOCK)

# For implementing non-blocking IO
def read_pipe_non_blocking(input_pipe, size):
    try:
        in_buffer = os.read(input_pipe, size)
    except OSError as err:
        if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK:
            in_buffer = None
        else:
            raise  # something else has happened -- better reraise
    return in_buffer

def get_azimuth(input_pipe):
    in_buffer = read_pipe_non_blocking(input_pipe, 1)
    print(in_buffer)
    if(in_buffer is None):
        sys.stderr.write("n")
        return ""
    else:
        tmp_buffer = None
        while(tmp_buffer != "a"):
            sys.stderr.write("m")
            time.sleep(0.1)
            tmp_buffer = read_pipe_non_blocking(input_pipe, 1)
            if(tmp_buffer != None and tmp_buffer != "a"):
                in_buffer += tmp_buffer
        read_pipe_non_blocking(input_pipe, 1) #Read in the newline character and the toss it
        sys.stderr.write("\nReturning \{%s\}" %in_buffer)
        return in_buffer


i = 0
while 1:
    print i
    time.sleep(1)
    i += 1
    get_azimuth(io)

此代码已直接从我的代码中复制粘贴,并不是那么清楚。如果有人需要澄清,请发表评论。