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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
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 includingtell()
.Note that indirect methods such as
len(fd.getvalue())
orfd.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.You can use
getvalue()
Example:
See: https://docs.python.org/2/library/io.html#io.BytesIO.getvalue