2012-03-29 25 views
0

我已經通過文檔搜索和搜索周圍,但沒有什麼關於阻止StringIO對象的說。有沒有辦法讓StringIO讀取阻塞

我可以創建自己的類似文件的對象,只是簡單地將StringIO包裝起來,但如何才能使其被阻塞?我知道的唯一方法是使用while循環和time.sleep(0.1)直到有數據可用。

+1

什麼會阻止它?你正在閱讀一個字符串。 – kindall 2012-03-29 16:45:28

+0

StringIO是一個類似文件的對象,所以它都有一個EOF和一個.close()方法,使所有其他的read()引發一個異常,我希望EOF只是阻塞而不是..返回一個EOF。 – Wessie 2012-03-29 16:50:53

+0

也許你想要一個管道,然後。 – 2012-03-29 16:55:25

回答

3
import os 

r, w = os.pipe() 
r, w = os.fdopen(r, 'rb'), os.fdopen(w, 'wb') 

正如我所需要的那樣工作,這個管道功能可悲地不是v在文檔中顯而易見,所以我以後只能找到它。

0

沒有,這是很明顯的看的read()

def read(self, n = -1): 
    """Read at most size bytes from the file 
    (less if the read hits EOF before obtaining size bytes). 

    If the size argument is negative or omitted, read all data until EOF 
    is reached. The bytes are returned as a string object. An empty 
    string is returned when EOF is encountered immediately. 
    """ 
    _complain_ifclosed(self.closed) 
    if self.buflist: 
     self.buf += ''.join(self.buflist) 
     self.buflist = [] 
    if n is None or n < 0: 
     newpos = self.len 
    else: 
     newpos = min(self.pos+n, self.len) 
    r = self.buf[self.pos:newpos] 
    self.pos = newpos 
    return r 

的實施也有本說明在文件的頂部

Notes: 
- Using a real file is often faster (but less convenient). 

所以,你可以使用一個真正的文件會更好無論如何