- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想实现一个继承自 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 中使用直接的方法复制文件通常是这样的: def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file
我想实现一个继承自 RawIOBase 的类.我正在努力实现 readinto 方法。基本上,我不知道如何更改 bytearray 的内容作为参数传递的对象。 我试过以下(天真的)方法: def re
我最近遇到了file对象的readinto方法(在Python 2.7中),它类似于C中的fread。它在某些情况下似乎很方便和强大。我计划使用它将多个文件读取到一个预分配的 numpy 数组中不复制
我一直在我的代码中使用 pySerial 3.4 从串行端口(准确地说是 RFID 芯片读取器/写入器)提取数据。我需要向阅读器发送命令,然后从阅读器读取结果。 基本上,我正在编写一个 12 字节的命
当我使用 ctypes 读取二进制数据时,它无法正常工作。 二进制数据 03 00 00 00 49 7B 00 00 00 00 00 00 Python 代码 from ctypes import
我正在按照此处的示例尝试处理二进制格式: http://dabeaz.blogspot.jp/2009/08/python-binary-io-handling.html >>> from ctype
我们有一些由 C 程序创建的二进制文件。 一种类型的文件是通过调用 fwrite 将以下 C 结构写入文件来创建的: typedef struct { unsigned long int foo
因此,我尝试迭代 tar 中的多个文件,然后将该数据加载到一些 ctype structures's I've defined 中。 。这对于非 tar 文件工作得很好,但后来我发现 ExFileOb
我尝试使用 websockets 测试我的 flask web 应用程序我的代码运行良好,但是当我在浏览器中重新加载页面两次或更多次时。我在终端 OSError 中。而且这个错误不会阻止 flask
我有一个非常基本的 http.server.HTTPServer 实现,我正在 Python 3.6 中启动。我正在使用它根据 google Analytics API 对 OAuth2 进行身份验证
我是一名优秀的程序员,十分优秀!