相关疑难解决方法(0)

如何将iterable转换为流?

如果我有一个包含字符串的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 iterator stream

12
推荐指数
3
解决办法
9234
查看次数

如何从生成器中读取tarfile?

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

python generator tar bytesio python-2.7

7
推荐指数
1
解决办法
372
查看次数

标签 统计

python ×2

bytesio ×1

generator ×1

iterator ×1

python-2.7 ×1

stream ×1

tar ×1