Gzip和子进程'在python中的stdout

问题描述 投票:1回答:4

我正在使用python 2.6.4并发现我不能像我希望的那样使用gzip和子进程。这说明了问题:

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

这里的内容更少

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

它看起来像是作为文本放入stdout然后放入一个空的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
4个回答
7
投票

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


3
投票

只是管道那个傻瓜

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()

1
投票

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

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

-1
投票

你不需要使用subprocess写入gzip.GzipFile。相反,像任何其他类似文件的对象一样写入它。结果是自动gzip压缩!

import gzip
with gzip.open("tmp.gz", "wb") as fh:
    fh.write('echo HI')
© www.soinside.com 2019 - 2024. All rights reserved.