有没有办法让StringIO.readlines()阻塞,直到流关闭或者通过write()使新数据可用?
我正在针对一个接口编写代码,该接口需要像对象一样的阻塞文件,并且在我向StringIO实例写入数据之前它会立即返回。使用initial_value参数也是不可取的,因为我需要使用中间结果。
或者,在python中有没有像fifo/stream这样的(文本)文件?
发布于 2013-05-01 23:16:57
如果你使用threads,那么你应该使用Queue。如果你使用其他的结构来进行线程间的通信,你肯定会遇到这样的麻烦,这将为你省去很多麻烦。
如果只需要readlines()和write(),那么可以包装Queue
class QueueStream(object):
def __init__(self):
self._queue = Queue()
def write(self, line):
self._queue.put(line)
def readlines(self):
while True:
item = self._queue.get()
yield item
self._queue.task_done()https://stackoverflow.com/questions/16319107
复制相似问题