[英]python subprocess with gzip
我正在嘗試通過子進程將 stream 數據壓縮並寫入文件。 以下作品。 我想知道是否可以改用 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 package? 我非常想知道為什么以下內容會給我一個文本文件(而不是壓縮的二進制版本)......非常奇怪。
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
底層文件對象的回報FD :
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
由於您只是指定要為正在執行的進程提供的文件句柄,因此文件對象不涉及其他方法。 要解決它,您可以將輸出寫入管道並從中讀取,如下所示:
oFid = gzip.open(filtSortFile, 'wb')
sort = subprocess.Popen(args="sort ", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
oFid.writelines(sort.stdout)
oFid.close()
是的,可以改用 python 的本機 gzip 庫。 我建議看看這個問題: gzip a file in Python 。
我現在正在使用Jace Browning 的回答:
with open('path/to/file', 'rb') as src, gzip.open('path/to/file.gz', 'wb') as dst:
dst.writelines(src)
盡管有評論提出您必須將src
內容轉換為bytes
,但此代碼不需要這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.