Vir*_*hiu 7 python generator tar bytesio python-2.7
在Python中用生成器创建一个zip文件?描述了从一堆文件中将.zip写入磁盘的解决方案.
我在相反的方向上有类似的问题.我被给了一个发电机:
stream = attachment.iter_bytes()
print type(stream)
Run Code Online (Sandbox Code Playgroud)
而且我想将它管道传输到tar gunzip文件对象:
b = io.BytesIO(stream)
f = tarfile.open(mode='r:gz', fileobj = b)
f.list()
Run Code Online (Sandbox Code Playgroud)
但我不能:
<type 'generator'>
Error: 'generator' does not have the buffer interface
Run Code Online (Sandbox Code Playgroud)
我可以在shell中解决这个问题:
$ curl --options http://URL | tar zxf - ./path/to/interesting_file
Run Code Online (Sandbox Code Playgroud)
如何在给定条件下在Python中执行相同的操作?
小智 5
我必须将生成器包装在构建在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())
Run Code Online (Sandbox Code Playgroud)
这样,您就可以打开 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
372 次 |
| 最近记录: |