我正在使用 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
这是 less 里面的样子
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
这是怎么回事?
更新: 这个较早的问题是在问同样的事情:Can I use an opened gzip file with Popen in Python?
最佳答案
subprocess
不能使用类文件,只能使用真实文件。 GzipFile
的 fileno()
方法返回基础文件的 FD,因此这就是 echo 重定向到的地方。然后 GzipFile 关闭,写入一个空的 gzip 文件。
关于python - python 中的 Gzip 和子进程的标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2853339/