python - 如何实现 readinto() 方法

标签 python python-bytearray

我想实现一个继承自 RawIOBase 的类.我正在努力实现 readinto 方法。基本上,我不知道如何更改 bytearray 的内容作为参数传递的对象。

我试过以下(天真的)方法:

def readinto(self, b):
    data = self.read(len(b))
    b = data
    return len(data)

但是,正如我怀疑的那样,这会将新的 bytearray 对象分配给局部变量 b 并且它不会更改原始 bytearray 的内容.

最佳答案

来自 RawIOBase.readinto 的文档:

Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. If the object is in non-blocking mode and no bytes are available, None is returned.

它有点困惑,但你需要写入 bytes-like对象 b(未读取)

示例用法

import io

class MyIO(io.RawIOBase):
    def readinto(self, b):
        msg = b'hello'
        b[:len(msg)] = msg
        return len(msg)

i = MyIO()
buf = bytearray()
i.readinto(buf)
print(buf)

看一下 BytesIO.readinto 的 CPython 实现. 基本上它会从对象的缓冲区到函数输入缓冲区。

关于python - 如何实现 readinto() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45805111/

相关文章:

python - 查找两个字符串(名称)之间的余弦相似度

Python 装饰器处理文档字符串

python - 从 vtkActor 更新 vtkPolyData

python - 如何将数字列表转换为字符串?

python - 在子类中强制使用类变量

python - 更快的字节数组列表理解/转换?

python - 是什么导致将空值插入到我的字节数组中?

python - 如何将 base64 字符串直接解码为二进制音频格式