我想从 BytesIO 对象获取确切的块数量,与 read() 工作的块相同。
我发现的最接近的方法是:
readable = io.BytesIO(b'\xff\xd8')
print(sys.getsizeof(readable))
然而,2 的 insetad 结果是 48
io.BytesIO
是一个流。使用它来获取内容的大小:
>>> sys.getsizeof(io.BytesIO(b'\xff\xd8').getvalue())
35
如果你想得到它的长度,请使用
len()
而不是 sys.getsizeof
:
>>> len(io.BytesIO(b'\xff\xd8').getvalue())
2
或手动读取特定字节数,这样您就可以事先知道大小:
>>> io.BytesIO(b'\xff\xd8').read(2)
b'\xff\xd8'
>>> sys.getsizeof(io.BytesIO(b'\xff\xd8').read(2))
35
>>> len(io.BytesIO(b'\xff\xd8').read(2))
2
由于这是一个流,因此在使用流之前无法知道大小。
您的代码没有得到
2
的原因是因为您询问的是 BytesIO
实例的大小而不是流值的大小:
>>> readable = io.BytesIO(b'\xff\xd8')
>>> readable
<_io.BytesIO object at 0x0000024A8CFC3BD0>
>>> sys.getsizeof(readable)
115