How to construct a TarFile object in memory from byte buffer in Python 3?

≡放荡痞女 提交于 2019-11-27 02:36:23

问题


Is it possible to create a TarFile object in memory using a buffer containing the tar data without having to write the TarFile to disk and open it up again? We get the bytes sent over a socket.

Something like this:

import tarfile
byte_array = client.read_bytes()
tar = tarfile.open(byte_array) # how to do this?
# use "tar" as a regular TarFile object
for member in tar.getmembers():
    f = tar.extractfile(member)
    print(f)

Note: one of the reasons for doing this is that we eventually want to be able to do this with multiple threads simultaneously, so using a temp file might be overridden if two threads try to do it at the same time.

Thank you for any and all help!


回答1:


BytesIO() from IO module does exactly what you need.

import tarfile, io
byte_array = client.read_bytes()
file_like_object = io.BytesIO(byte_array)
tar = tarfile.open(fileobj=file_like_object)
# use "tar" as a regular TarFile object
for member in tar.getmembers():
    f = tar.extractfile(member)
    print(f)



回答2:


Sure, something like this:

import io

io_bytes = io.BytesIO(byte_array)

tar = tarfile.open(fileobj=io_bytes, mode='r')

(Adjust mode to fit the format of your tar file, e.g. possibly `mode='r:gz', etc.)



来源:https://stackoverflow.com/questions/15857792/how-to-construct-a-tarfile-object-in-memory-from-byte-buffer-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!