如何从生成器读取 tarfile?

How do I read a tarfile from a generator?

Create a zip file from a generator in Python? 描述了将一堆文件写入 .zip 到磁盘的解决方案。

我在相反的方向也有类似的问题。我得到了一台发电机:

stream = attachment.iter_bytes()
print type(stream)

我很乐意将其传输到 tar gunzip 文件之类的对象:

b = io.BytesIO(stream)
f = tarfile.open(mode='r:gz', fileobj = b)
f.list()

但我不能:

<type 'generator'>
Error: 'generator' does not have the buffer interface

我可以像这样在 shell 中解决这个问题:

$ curl --options http://URL | tar zxf - ./path/to/interesting_file

如何在给定条件下在 Python 中执行相同的操作?

我不得不将生成器包装在一个构建在 io 模块之上的类似文件的对象中。

def generator_to_stream(generator, buffer_size=io.DEFAULT_BUFFER_SIZE):
    class GeneratorStream(io.RawIOBase):
        def __init__(self):
            self.leftover = None

        def readable(self):
            return True

        def readinto(self, b):
            try:
                l = len(b)  # : We're supposed to return at most this much
                chunk = self.leftover or next(generator)
                output, self.leftover = chunk[:l], chunk[l:]
                b[:len(output)] = output
                return len(output)
            except StopIteration:
                return 0  # : Indicate EOF
    return io.BufferedReader(GeneratorStream())

有了这个,您可以打开 tar 文件并提取其内容。

stream = generator_to_stream(any_stream)
tar_file = tarfile.open(fileobj=stream, mode='r|*')
#: Do whatever you want with the tar_file now

for member in tar_file:
    member_file = tar_file.extractfile(member)