如何从生成器中读取tarfile?

时间:2016-08-25 22:54:59

标签: python python-2.7 generator tar bytesio

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中执行相同操作?

1 个答案:

答案 0 :(得分:2)

我不得不将生成器包装在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)