I'm trying to figure out the best way to compress a stream with Python's zlib
.
I've got a file-like input stream (input
, below) and an output function which accepts a file-like (output_function
, below):
with open("file") as input:
output_function(input)
And I'd like to gzip-compress input
chunks before sending them to output_function
:
with open("file") as input:
output_function(gzip_stream(input))
It looks like the gzip module assumes that either the input or the output will be a gzip'd file-on-disk… So I assume that the zlib module is what I want.
However, it doesn't natively offer a simple way to create a stream file-like… And the stream-compression it does support comes by way of manually adding data to a compression buffer, then flushing that buffer.
Of course, I could write a wrapper around zlib.Compress.compress
and zlib.Compress.flush
(Compress
is returned by zlib.compressobj()
), but I'd be worried about getting buffer sizes wrong, or something similar.
So, what's the simplest way to create a streaming, gzip-compressing file-like with Python?
Edit: To clarify, the input stream and the compressed output stream are both too large to fit in memory, so something like output_function(StringIO(zlib.compress(input.read())))
doesn't really solve the problem.