2010-05-17 81 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()