2012-03-29 26 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). 

所以,你可以使用一个真正的文件会更好无论如何