2010-05-17 84 views
1

我正在使用python 2.6.4,并发现我无法像我希望的那样对子进程使用gzip。这说明了一个问题:这里是什么样子里面少python中的Gzip和子进程'stdout

​​

它看起来像它放在标准输出为文本,然后放入一个空的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 

。事实上,如果我删除“嗨\ 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 

这到底是怎么回事?

UPDATE: 这较早前的问题是问同样的事情:与subprocess,唯一真正的文件Can I use an opened gzip file with Popen in Python?

回答

7

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

+1

我想我是通过gzip管道然后。 – 2010-05-17 22:53:03

-1

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

1

我不能完全肯定这是为什么不工作(也许是输出重定向并没有叫Python的写,这是gzip的作品有?),但这个工程:

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

对于一个非常大的文件,这可能会导致内存问题 – fodon 2011-09-17 13:42:36

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