有没有办法使StringIO读取阻塞

时间:2012-03-29 16:41:43

标签: python blocking stringio

我搜索了文档并搜索过,但没有任何关于阻止StringIO对象的说法。

我可以创建自己的类似文件的对象,只是简单地包装StringIO但是如何阻止它?我知道的唯一方法是使用while循环和time.sleep(0.1),直到有数据可用。

2 个答案:

答案 0 :(得分:7)

import os

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

完全按照我的需要工作,这个管道功能在文档中很遗憾,所以我后来才发现它。

答案 1 :(得分: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).

所以你最好还是使用真正的文件