从Python生成器创建zip文件?描述从一堆文件中写入.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)