如何在Python 3中从字节缓冲区在内存中构造TarFile对象? [英] How to construct a TarFile object in memory from byte buffer in Python 3?

查看:121
本文介绍了如何在Python 3中从字节缓冲区在内存中构造TarFile对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用包含tar数据的缓冲区在内存中创建TarFile对象,而不必将TarFile写入磁盘并再次打开它?我们得到通过套接字发送的字节.

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.

类似这样的东西:

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)

注意:这样做的原因之一是我们最终希望能够同时对多个线程执行此操作,因此如果两个线程尝试同时执行,则使用temp文件可能会被覆盖.

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.

感谢您的所有帮助!

推荐答案

来自 IO模块完全满足您的需求.

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)

这篇关于如何在Python 3中从字节缓冲区在内存中构造TarFile对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆