如果我有一个包含字符串的iterable,是否有一种简单的方法可以将其转换为流?我想做这样的事情:
def make_file():
yield "hello\n"
yield "world\n"
output = tarfile.TarFile(…)
stream = iterable_to_stream(make_file())
output.addfile(…, stream)
Run Code Online (Sandbox Code Playgroud) 在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中执行相同的操作?