2013-11-26 19 views
0

this question中,提問者已經解決了以非阻塞方式從命名管道讀取的問題,但他使用了固定的緩衝區大小。有沒有辦法做到這一點,沒有一個固定的緩衝區大小,只是等待另一端用一個換行符來終止它們自己的緩衝區?無阻塞地讀取(os.read)FIFO沒有固定緩衝區大小

+0

你知道'os.read(fd,size)'*可能會返回少於* size的字節嗎? (無論阻擋/非阻擋fd) – jfs

+0

我不知道。這樣就解決了我的問題。我應該把問題留給更通用的案例嗎?還是隻接受你的建議作爲答案? – Seanny123

+0

如果你認爲它解決了你的問題;你可以把你的思考過程作爲答案並接受它。它可能有助於來自谷歌的未來訪客。 – jfs

回答

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) 

此代碼已直接從我的代碼複製粘貼,並沒有真正清楚。如果有人需要澄清,請發表評論。