4

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

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

4

2 回答 2

6
import os

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

完全按照我的需要工作,遗憾的是,这个管道函数在文档中不是很明显,所以我后来才发现它。

于 2012-03-30T07:52:22.857 回答
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).

因此,无论如何您最好还是使用真实文件

于 2012-03-29T17:54:39.960 回答