From 79c5ef11d56e761445e334a7121764808e9e70cf Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Tue, 17 Aug 2010 21:10:05 +0000 Subject: Issue #3488: Provide convenient shorthand functions `gzip.compress` and `gzip.decompress`. Original patch by Anand B. Pillai. --- Lib/gzip.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) (limited to 'Lib/gzip.py') diff --git a/Lib/gzip.py b/Lib/gzip.py index fab55a3015d..83311cc0deb 100644 --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -10,7 +10,7 @@ import zlib import builtins import io -__all__ = ["GzipFile","open"] +__all__ = ["GzipFile", "open", "compress", "decompress"] FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16 @@ -476,6 +476,23 @@ class GzipFile(io.BufferedIOBase): return b''.join(bufs) # Return resulting line +def compress(data, compresslevel=9): + """Compress data in one shot and return the compressed string. + Optional argument is the compression level, in range of 1-9. + """ + buf = io.BytesIO() + with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel) as f: + f.write(data) + return buf.getvalue() + +def decompress(data): + """Decompress a gzip compressed string in one shot. + Return the decompressed string. + """ + with GzipFile(fileobj=io.BytesIO(data)) as f: + return f.read() + + def _test(): # Act like gzip; with -d, act like gunzip. # The input file is not deleted, however, nor are any other gzip -- cgit v1.2.3