【问题标题】:Decompress stdout from a subprocess Popen call using gzip使用 gzip 从子进程 Popen 调用中解压缩标准输出
【发布时间】:2011-12-21 14:03:47
【问题描述】:

是否可以使用 gzip 直接解压缩通过 subprocess.Popen 触发的命令的标准输出?

我试过了,但它不起作用:

import subprocess
pipe = subprocess.Popen(["cat tmp.txt | gzip --stdout"], stdout=subprocess.PIPE)

import gzip
output = gzip.open(pipe.stdout)

while output.readline().rstrip():
    # Do something

有什么想法吗?

【问题讨论】:

    标签: python gzip subprocess pipe iostream


    【解决方案1】:

    可以通过创建将打开的文件而不是文件名传递给 Python 的 gzip 库 直接使用 gzip.GzipFile 实例,而不是使用帮助程序 gzip.open 函数。但是,Python 的 gzip 需要一个可搜索的文件,并且会在子进程使用的流上失败。

    创建GzipFile实例的方式是

    output = gzip.GzipFile(fileobj=pipe.stdout)

    但这不起作用,因为该类需要一个可查找的文件对象。如果等待所有子进程输出并将数据缓存在内存中没有问题,则可以使用 StringIO 解决此问题,例如:

    import StringIO, subprocess
    pipe = subprocess.Popen(["cat bla3.txt | gzip --stdout"], stdout=subprocess.PIPE, shell=True)
    helper = StringIO.StringIO()     
    helper.write(pipe.stdout.read())
    helper.seek(0)
    output = gzip.GzipFile(fileobj=helper) 
    

    如果你不能这样做,你将不得不从 Python 的 gzip.py 中复制一些代码,并自己处理数据和对内部 zlib 的调用。

    【讨论】:

    • 我已经尝试过您的解决方案,但我收到此错误:helper.write(pipe.stdout.read()) TypeError: unbound method write() must be called with StringIO instance as first argument (得到了 str 实例)
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2010-11-20
    • 2020-07-05
    • 2014-08-28
    相关资源
    最近更新 更多