【问题标题】:Gzip and subprocess' stdout in pythonpython中的Gzip和子进程的标准输出
【发布时间】:2019-04-26 22:16:56
【问题描述】:

我正在使用 python 2.6.4 并发现我不能像我希望的那样将 gzip 与 subprocess 一起使用。这说明了问题:

May 17 18:05:36> python
Python 2.6.4 (r264:75706, Mar 10 2010, 14:41:19)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.

>>> import gzip
>>> import subprocess
>>> fh = gzip.open("tmp","wb")
>>> subprocess.Popen("echo HI", shell=True, stdout=fh).wait()
0
>>> fh.close()
>>>
[2]+  Stopped                 python
May 17 18:17:49> file tmp
tmp: data
May 17 18:17:53> less tmp
"tmp" may be a binary file.  See it anyway?
May 17 18:17:58> zcat tmp

zcat: tmp: not in gzip format

这是less里面的样子

HI
^_<8B>^H^Hh<C0><F1>K^B<FF>tmp^@^C^@^@^@^@^@^@^@^@^@

看起来它作为文本放入标准输出,然后放入一个空的 gzip 文件。事实上,如果我删除“Hi\n”,那么我会得到这个:

May 17 18:22:34> file tmp
tmp: gzip compressed data, was "tmp", last modified: Mon May 17 18:17:12 2010, max compression

这是怎么回事?

更新: 这个早先的问题问的是同样的事情:Can I use an opened gzip file with Popen in Python?

【问题讨论】:

    标签: python gzip subprocess


    【解决方案1】:

    subprocess 不能使用类似文件,只能使用真实文件。 GzipFilefileno() 方法返回底层文件的 FD,这就是 echo 重定向到的内容。 GzipFile 然后关闭,写入一个空的 gzip 文件。

    【讨论】:

    • 我想我正在通过 gzip 进行管道传输。
    【解决方案2】:

    只是管那个吸盘

    from subprocess import Popen,PIPE
    GZ = Popen("gzip > outfile.gz",stdin=PIPE,shell=True)
    P = Popen("echo HI",stdout=GZ.stdin,shell=True)
    # these next three must be in order
    P.wait()
    GZ.stdin.close()
    GZ.wait()
    

    【讨论】:

      【解决方案3】:

      我不完全确定为什么这不起作用(也许输出重定向没有调用 python 的写入,这是 gzip 的作用?)但这有效:

      >>> fh.write(subprocess.Popen("echo Hi", shell=True, stdout=subprocess.PIPE).stdout.read())
      

      【讨论】:

      • 对于一个非常大的文件,这可能会导致内存问题
      【解决方案4】:

      您无需使用subprocess 来写信给gzip.GzipFile。相反,像任何其他类似文件的对象一样写入它。结果会自动压缩!

      import gzip
      with gzip.open("tmp.gz", "wb") as fh:
          fh.write('echo HI')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-29
        • 2018-03-08
        • 1970-01-01
        • 2010-11-19
        • 2016-12-01
        • 2021-02-06
        • 1970-01-01
        • 2015-01-20
        相关资源
        最近更新 更多