使用gzip的python子进程

时间:2011-09-17 04:26:50

标签: python gzip

我正在尝试通过子进程传输数据,gzip并写入文件。 以下作品。我想知道是否可以使用python的本机gzip库。

fid = gzip.open(self.ipFile, 'rb') # input data
oFid = open(filtSortFile, 'wb') # output file
sort = subprocess.Popen(args="sort | gzip -c ", shell=True, stdin=subprocess.PIPE, stdout=oFid) # set up the pipe
processlines(fid, sort.stdin, filtFid) # pump data into the pipe

问题:我该怎么做呢......在哪里使用python的gzip包?我很想知道为什么以下给我一个文本文件(而不是压缩的二进制版本)...非常奇怪。

fid = gzip.open(self.ipFile, 'rb')
oFid = gzip.open(filtSortFile, 'wb')
sort = subprocess.Popen(args="sort ", shell=True, stdin=subprocess.PIPE, stdout=oFid)
processlines(fid, sort.stdin, filtFid)

2 个答案:

答案 0 :(得分:4)

subprocess写入oFid.fileno(),但gzip returns fd of underlying file object

def fileno(self):
    """Invoke the underlying file object's fileno() method."""
    return self.fileobj.fileno()

要直接启用压缩使用gzip方法:

import gzip
from subprocess import Popen, PIPE
from threading import Thread

def f(input, output):
    for line in iter(input.readline, ''):
        output.write(line)

p = Popen(["sort"], bufsize=-1, stdin=PIPE, stdout=PIPE)
Thread(target=f, args=(p.stdout, gzip.open('out.gz', 'wb'))).start()

for s in "cafebabe":
    p.stdin.write(s+"\n")
p.stdin.close()

实施例

$ python gzip_subprocess.py  && od -c out.gz && zcat out.gz 
0000000 037 213  \b  \b 251   E   t   N 002 377   o   u   t  \0   K 344
0000020   J 344   J 002 302   d 256   T       L 343 002  \0   j 017   j
0000040   k 020  \0  \0  \0
0000045
a
a
b
b
c
e
e
f

答案 1 :(得分:2)

由于您只是指定了要执行的进程的文件句柄,因此文件对象不涉及其他方法。要解决它,您可以将输出写入管道并从中读取,如下所示:

oFid = gzip.open(filtSortFile, 'wb')
sort = subprocess.Popen(args="sort ", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
oFid.writelines(sort.stdout)
oFid.close()