簡體   English   中英

python中的Gzip和子進程的標准輸出

[英]Gzip and subprocess' stdout in python

我正在使用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^@^@^@^@^@^@^@^@^@

看起來像將它作為文本放入標准輸出中,然后放入一個空的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

這里發生了什么?

更新:這個更早的問題在問同樣的事情: 我可以在Python中將打開的gzip文件與Popen一起使用嗎?

您不能將文件喜歡與subprocess一起使用,只能使用真實文件。 GzipFilefileno()方法返回基礎文件的FD,這就是echo重定向到的文件。 然后關閉GzipFile,寫入一個空的gzip文件。

只是管那個吸盤

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

我不完全確定為什么這不起作用(也許輸出重定向沒有調用python的write,這就是gzip的工作原理?),但是這可行:

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

您不需要使用subprocess gzip.GzipFile來寫入gzip.GzipFile 而是像其他任何類似文件的對象一樣對其進行寫入。 結果會自動壓縮!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM