gpt4 book ai didi

带有 gzip 的 python 子进程

转载 作者:太空狗 更新时间:2023-10-30 02:34:35 26 4
gpt4 key购买 nike

我正在尝试通过子进程流式传输数据,对其进行 gzip 压缩并写入文件。以下作品。我想知道是否可以改用 python 的 native 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)

最佳答案

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

关于带有 gzip 的 python 子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7452427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com