相当于 Python 2 中 BytesIO 的 getbuffer [英] equivalent of getbuffer for BytesIO in Python 2
问题描述
在 Python 3 中,我可以通过 object.getbuffer().nbytes
(其中 object = ByteIO()
)获取 ByteIO 对象的大小,但是什么会是 Python 2 中 getbuffer()
的最佳等价物吗?做了一些探索,我发现我可以使用 len(object.getvalue())
或 sys.getsizeof(object)
,但我不知道 Python 2 是否会接受他们.
查看下面的重要更新
在挖掘 python 2.7 源代码后,我找到了一个简单的解决方案:因为 io.BytesIO()
返回一个文件描述符,它有一组标准的函数,包括 tell()代码>.
请注意,诸如 len(fd.getvalue())
或 fd.getbuffer().nbytes
等间接方法将缓冲区复制出来,然后计算缓冲区大小.就我而言,当缓冲区占用 1/2 的内存时,这最终会导致应用程序崩溃:/
相反 fd.tell()
只报告描述符的当前位置,不需要任何内存分配!
请注意,sys.getsizeof(fd)
、fd.__sizeof__()
都没有返回正确的缓冲区大小.
更新
在@admaster 和@Artemis 评论之后,我意识到正确的方法,在预设缓冲区的情况下,是将指针移动到缓冲区的末尾.标准的seek
函数可以做到这一点,蚂蚁会报告当前缓冲区大小
buffsize = fd.seek(0,2)
那么这里应该如何在没有不必要的应对记忆的情况下完成
from io import BytesIOx = BytesIO(b'AAAAAA')x.seek(0,2) # 返回 6x.tell() # 返回 6# 然而x = BytesIO()x.write(b'AAAAAA')x.seek(0,2) # 返回 6x.tell() # 返回 6
In Python 3, I can get the size of a ByteIO object via object.getbuffer().nbytes
(where object = ByteIO()
), but what would be the best equivalent for getbuffer()
in Python 2? Doing some exploring, I found out I can use len(object.getvalue())
or sys.getsizeof(object)
, but I don't know if Python 2 will accept them.
see critical update below
After digging in python 2.7 source code I found a simple solution: because io.BytesIO()
returns a file descriptor, it has a standard set of functions including tell()
.
Note that indirect methods such as len(fd.getvalue())
or fd.getbuffer().nbytes
copy buffer out and then compute buffer size. In my case, when the buffer holds 1/2 of the memory, this ends up as an application crash :/
Contrary fd.tell()
just reports a current position of the descriptor and do not need any memory allocation!
Note that both sys.getsizeof(fd)
, fd.__sizeof__()
do not return correct bufer size.
>>> from io import BytesIO
>>> from sys import getsizeof
>>> with BytesIO() as fd:
... for x in xrange(200):
... fd.write(" ")
... print fd.tell(), fd.__sizeof__(), getsizeof(fd)
1 66 98
2 66 98
3 68 100
4 68 100
5 70 102
6 70 102
.....
194 265 297
195 265 297
196 265 297
197 265 297
198 265 297
199 265 297
200 265 297
UPDATE
After @admaster and @Artemis comments I realized that the correct method, in case of preset buffer, is to move the pointer to the end of the buffer. Standard seek
function can do that, ant it will report the current buffer size
buffsize = fd.seek(0,2)
So here how it should be done without unnecessary coping memory
from io import BytesIO
x = BytesIO(b'AAAAAA')
x.seek(0,2) # returns 6
x.tell() # returns 6
# However
x = BytesIO()
x.write(b'AAAAAA')
x.seek(0,2) # returns 6
x.tell() # returns 6
这篇关于相当于 Python 2 中 BytesIO 的 getbuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!