Gzip和子进程'在python中的stdout

pyt*_*hor 1 python gzip subprocess

我正在使用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
Run Code Online (Sandbox Code Playgroud)

这里的内容更少

HI
^_<8B>^H^Hh<C0><F1>K^B<FF>tmp^@^C^@^@^@^@^@^@^@^@^@
Run Code Online (Sandbox Code Playgroud)

它看起来像是作为文本放入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
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

更新: 这个早期的问题是同样的问题:我可以在Python中使用带有Popen的已打开的gzip文件吗?

Ign*_*ams 7

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


amw*_*ter 6

只是管那个吸盘

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()
Run Code Online (Sandbox Code Playgroud)