带有gzip的python子进程

fod*_*don 5 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
Run Code Online (Sandbox Code Playgroud)

问题:我该怎么做……在使用 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)
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 6

subprocess写入oFid.fileno()gzip返回底层文件对象的 fd

def fileno(self):
    """Invoke the underlying file object's fileno() method."""
    return self.fileobj.fileno()
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

例子

$ 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
Run Code Online (Sandbox Code Playgroud)