繁体   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