python有某种消费流吗?

2024-04-26 22:32:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中寻找一个“消耗”字节流,其行为类似于Queue:数据将在流的末尾写入,而读取将返回并丢弃流开头的数据

我还没有找到这样的东西(使用消费/旋转/移动流之类的关键字),所以我觉得我在这里可能没有使用正确的术语

它的肮脏实现可能是:

from io import BytesIO, SEEK_END

class ConsumingStream(BytesIO):
    """ Stream where write append data to the end and read consumes from the start """

    def write(self, data):
        """ Write bytes to the end of the stream """
        self.seek(0, SEEK_END)
        super().write(data)

    def read(self, size=-1):
        """ Read and consume at most size-bytes from the beginning of the stream """
        self.seek(0)
        data = super().read(size)
        self.shift(len(data))
        return data

    def shift(self, n):
        """ Removes n-bytes from the beginning of the buffer """
        view = self.getbuffer()
        size = len(view)
        view[0:size-n] = view[n:size]
        view.release()
        self.truncate(size-n)

s = ConsumingStream(b'first_second_third')
print(s.read(6))    # first_
print(s.getvalue()) # second_third

理想情况下,流将实现一个getbuffer()方法(就像这里的BytesIO)并且是线程安全的(我没有在脏的实现中添加锁)

python中有这样的流吗?如果没有,最有效的执行方法是什么


Tags: ofthe数据fromselfviewreaddata