blob: aa8386e5fe848aef814f422bf28a66c8523ce849 [file] [log] [blame]
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00001"""Functions that read and write gzipped files.
2
Guido van Rossum54f22ed2000-02-04 15:10:34 +00003The user of the file doesn't have to worry about the compression,
4but random access is not allowed."""
5
6# based on Andrew Kuchling's minigzip.py distributed with the zlib module
7
Tim Peters49667c22004-07-27 21:05:21 +00008import struct, sys, time
Guido van Rossum15262191997-04-30 16:04:57 +00009import zlib
Georg Brandl1a3284e2007-12-02 09:40:06 +000010import builtins
Guido van Rossum15262191997-04-30 16:04:57 +000011
Skip Montanaro2dd42762001-01-23 15:35:05 +000012__all__ = ["GzipFile","open"]
13
Guido van Rossum15262191997-04-30 16:04:57 +000014FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
15
16READ, WRITE = 1, 2
17
Tim Petersfb0ea522002-11-04 19:50:11 +000018def U32(i):
19 """Return i as an unsigned integer, assuming it fits in 32 bits.
20
21 If it's >= 2GB when viewed as a 32-bit unsigned int, return a long.
22 """
23 if i < 0:
Guido van Rossume2a383d2007-01-15 16:59:06 +000024 i += 1 << 32
Tim Petersfb0ea522002-11-04 19:50:11 +000025 return i
26
Tim Peters9288f952002-11-05 20:38:55 +000027def LOWU32(i):
28 """Return the low-order 32 bits of an int, as a non-negative int."""
Guido van Rossume2a383d2007-01-15 16:59:06 +000029 return i & 0xFFFFFFFF
Tim Peters9288f952002-11-05 20:38:55 +000030
Guido van Rossum15262191997-04-30 16:04:57 +000031def write32(output, value):
Jeremy Hyltonc19f9971999-03-23 23:05:34 +000032 output.write(struct.pack("<l", value))
Tim Peters07e99cb2001-01-14 23:47:14 +000033
Guido van Rossum95bdd0b1999-04-12 14:34:16 +000034def write32u(output, value):
Tim Petersfb0ea522002-11-04 19:50:11 +000035 # The L format writes the bit pattern correctly whether signed
36 # or unsigned.
Guido van Rossum95bdd0b1999-04-12 14:34:16 +000037 output.write(struct.pack("<L", value))
38
Guido van Rossum15262191997-04-30 16:04:57 +000039def read32(input):
Jeremy Hyltonc19f9971999-03-23 23:05:34 +000040 return struct.unpack("<l", input.read(4))[0]
Guido van Rossum15262191997-04-30 16:04:57 +000041
Fred Drakefa1591c1999-04-05 18:37:59 +000042def open(filename, mode="rb", compresslevel=9):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000043 """Shorthand for GzipFile(filename, mode, compresslevel).
44
45 The filename argument is required; mode defaults to 'rb'
46 and compresslevel defaults to 9.
47
48 """
Guido van Rossum15262191997-04-30 16:04:57 +000049 return GzipFile(filename, mode, compresslevel)
50
51class GzipFile:
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000052 """The GzipFile class simulates most of the methods of a file object with
Guido van Rossum97c5fcc2002-08-06 17:03:25 +000053 the exception of the readinto() and truncate() methods.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000054
55 """
Guido van Rossum15262191997-04-30 16:04:57 +000056
Guido van Rossum68de3791997-07-19 20:22:23 +000057 myfileobj = None
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +000058 max_read_chunk = 10 * 1024 * 1024 # 10Mb
Guido van Rossum68de3791997-07-19 20:22:23 +000059
Tim Peters07e99cb2001-01-14 23:47:14 +000060 def __init__(self, filename=None, mode=None,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000061 compresslevel=9, fileobj=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000062 """Constructor for the GzipFile class.
63
64 At least one of fileobj and filename must be given a
65 non-trivial value.
66
67 The new class instance is based on fileobj, which can be a regular
68 file, a StringIO object, or any other object which simulates a file.
69 It defaults to None, in which case filename is opened to provide
70 a file object.
71
72 When fileobj is not None, the filename argument is only used to be
73 included in the gzip file header, which may includes the original
74 filename of the uncompressed file. It defaults to the filename of
75 fileobj, if discernible; otherwise, it defaults to the empty string,
76 and in this case the original filename is not included in the header.
77
78 The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb',
79 depending on whether the file will be read or written. The default
80 is the mode of fileobj if discernible; otherwise, the default is 'rb'.
81 Be aware that only the 'rb', 'ab', and 'wb' values should be used
82 for cross-platform portability.
83
84 The compresslevel argument is an integer from 1 to 9 controlling the
85 level of compression; 1 is fastest and produces the least compression,
86 and 9 is slowest and produces the most compression. The default is 9.
87
88 """
89
Skip Montanaro12424bc2002-05-23 01:43:05 +000090 # guarantee the file is opened in binary mode on platforms
91 # that care about that sort of thing
92 if mode and 'b' not in mode:
93 mode += 'b'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000094 if fileobj is None:
Georg Brandl1a3284e2007-12-02 09:40:06 +000095 fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
Guido van Rossum68de3791997-07-19 20:22:23 +000096 if filename is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000097 if hasattr(fileobj, 'name'): filename = fileobj.name
98 else: filename = ''
Guido van Rossum68de3791997-07-19 20:22:23 +000099 if mode is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 if hasattr(fileobj, 'mode'): mode = fileobj.mode
Fred Drake9bb76d11999-04-05 18:33:40 +0000101 else: mode = 'rb'
Guido van Rossum68de3791997-07-19 20:22:23 +0000102
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000103 if mode[0:1] == 'r':
104 self.mode = READ
Tim Peters07e99cb2001-01-14 23:47:14 +0000105 # Set flag indicating start of a new member
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000106 self._new_member = True
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000107 self.extrabuf = b""
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000108 self.extrasize = 0
Thomas Wouterscf297e42007-02-23 15:07:44 +0000109 self.name = filename
Thomas Wouters477c8d52006-05-27 19:21:47 +0000110 # Starts small, scales exponentially
111 self.min_readsize = 100
Guido van Rossum15262191997-04-30 16:04:57 +0000112
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000113 elif mode[0:1] == 'w' or mode[0:1] == 'a':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000114 self.mode = WRITE
115 self._init_write(filename)
116 self.compress = zlib.compressobj(compresslevel,
Tim Peters07e99cb2001-01-14 23:47:14 +0000117 zlib.DEFLATED,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000118 -zlib.MAX_WBITS,
119 zlib.DEF_MEM_LEVEL,
120 0)
121 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000122 raise IOError("Mode " + mode + " not supported")
Guido van Rossum15262191997-04-30 16:04:57 +0000123
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000124 self.fileobj = fileobj
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000125 self.offset = 0
Guido van Rossum15262191997-04-30 16:04:57 +0000126
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000127 if self.mode == WRITE:
128 self._write_gzip_header()
Guido van Rossum15262191997-04-30 16:04:57 +0000129
Thomas Wouterscf297e42007-02-23 15:07:44 +0000130 @property
131 def filename(self):
132 import warnings
133 warnings.warn("use the name attribute", DeprecationWarning)
134 if self.mode == WRITE and self.name[-3:] != ".gz":
135 return self.name + ".gz"
136 return self.name
137
Guido van Rossum15262191997-04-30 16:04:57 +0000138 def __repr__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 s = repr(self.fileobj)
140 return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
Guido van Rossum15262191997-04-30 16:04:57 +0000141
142 def _init_write(self, filename):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000143 self.name = filename
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 self.crc = zlib.crc32("")
145 self.size = 0
146 self.writebuf = []
147 self.bufsize = 0
Guido van Rossum15262191997-04-30 16:04:57 +0000148
149 def _write_gzip_header(self):
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000150 self.fileobj.write(b'\037\213') # magic header
151 self.fileobj.write(b'\010') # compression method
Lars Gustäbel5590d8c2007-08-10 12:02:32 +0000152 try:
Lars Gustäbelead70562007-08-13 09:05:16 +0000153 # RFC 1952 requires the FNAME field to be Latin-1. Do not
154 # include filenames that cannot be represented that way.
155 fname = self.name.encode('latin-1')
156 if fname.endswith(b'.gz'):
157 fname = fname[:-3]
Lars Gustäbel5590d8c2007-08-10 12:02:32 +0000158 except UnicodeEncodeError:
Lars Gustäbelead70562007-08-13 09:05:16 +0000159 fname = b''
160 flags = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 if fname:
162 flags = FNAME
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000163 self.fileobj.write(chr(flags).encode('latin-1'))
Guido van Rossume2a383d2007-01-15 16:59:06 +0000164 write32u(self.fileobj, int(time.time()))
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000165 self.fileobj.write(b'\002')
166 self.fileobj.write(b'\377')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 if fname:
Lars Gustäbel5590d8c2007-08-10 12:02:32 +0000168 self.fileobj.write(fname + b'\000')
Guido van Rossum15262191997-04-30 16:04:57 +0000169
170 def _init_read(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000171 self.crc = zlib.crc32("")
172 self.size = 0
Guido van Rossum15262191997-04-30 16:04:57 +0000173
174 def _read_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000175 magic = self.fileobj.read(2)
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000176 if magic != b'\037\213':
Collin Winterce36ad82007-08-30 01:19:48 +0000177 raise IOError('Not a gzipped file')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 method = ord( self.fileobj.read(1) )
179 if method != 8:
Collin Winterce36ad82007-08-30 01:19:48 +0000180 raise IOError('Unknown compression method')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000181 flag = ord( self.fileobj.read(1) )
182 # modtime = self.fileobj.read(4)
183 # extraflag = self.fileobj.read(1)
184 # os = self.fileobj.read(1)
185 self.fileobj.read(6)
Guido van Rossum15262191997-04-30 16:04:57 +0000186
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000187 if flag & FEXTRA:
188 # Read & discard the extra field, if present
Tim Petersfb0ea522002-11-04 19:50:11 +0000189 xlen = ord(self.fileobj.read(1))
190 xlen = xlen + 256*ord(self.fileobj.read(1))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000191 self.fileobj.read(xlen)
192 if flag & FNAME:
193 # Read and discard a null-terminated string containing the filename
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000194 while True:
Tim Petersfb0ea522002-11-04 19:50:11 +0000195 s = self.fileobj.read(1)
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000196 if not s or s==b'\000':
Tim Petersfb0ea522002-11-04 19:50:11 +0000197 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 if flag & FCOMMENT:
199 # Read and discard a null-terminated string containing a comment
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000200 while True:
Tim Petersfb0ea522002-11-04 19:50:11 +0000201 s = self.fileobj.read(1)
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000202 if not s or s==b'\000':
Tim Petersfb0ea522002-11-04 19:50:11 +0000203 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 if flag & FHCRC:
205 self.fileobj.read(2) # Read & discard the 16-bit header CRC
Guido van Rossum15262191997-04-30 16:04:57 +0000206
207
208 def write(self,data):
Martin v. Löwisdb044892002-03-11 06:46:52 +0000209 if self.mode != WRITE:
210 import errno
211 raise IOError(errno.EBADF, "write() on read-only GzipFile object")
Tim Peters863ac442002-04-16 01:38:40 +0000212
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000213 if self.fileobj is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000214 raise ValueError("write() on closed GzipFile object")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000215 if len(data) > 0:
216 self.size = self.size + len(data)
217 self.crc = zlib.crc32(data, self.crc)
218 self.fileobj.write( self.compress.compress(data) )
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000219 self.offset += len(data)
Guido van Rossum15262191997-04-30 16:04:57 +0000220
Guido van Rossum56068012000-02-02 16:51:06 +0000221 def read(self, size=-1):
Martin v. Löwisdb044892002-03-11 06:46:52 +0000222 if self.mode != READ:
223 import errno
Brett Cannonedfb3022003-12-04 19:28:06 +0000224 raise IOError(errno.EBADF, "read() on write-only GzipFile object")
Tim Peters863ac442002-04-16 01:38:40 +0000225
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000226 if self.extrasize <= 0 and self.fileobj is None:
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000227 return b''
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000228
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000229 readsize = 1024
Guido van Rossum56068012000-02-02 16:51:06 +0000230 if size < 0: # get the whole thing
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000231 try:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000232 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000233 self._read(readsize)
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000234 readsize = min(self.max_read_chunk, readsize * 2)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000235 except EOFError:
236 size = self.extrasize
237 else: # just get some more of it
238 try:
239 while size > self.extrasize:
240 self._read(readsize)
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000241 readsize = min(self.max_read_chunk, readsize * 2)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000242 except EOFError:
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000243 if size > self.extrasize:
244 size = self.extrasize
Tim Peters07e99cb2001-01-14 23:47:14 +0000245
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 chunk = self.extrabuf[:size]
247 self.extrabuf = self.extrabuf[size:]
248 self.extrasize = self.extrasize - size
Guido van Rossum15262191997-04-30 16:04:57 +0000249
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000250 self.offset += size
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000251 return chunk
Guido van Rossum15262191997-04-30 16:04:57 +0000252
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000253 def _unread(self, buf):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000254 self.extrabuf = buf + self.extrabuf
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000255 self.extrasize = len(buf) + self.extrasize
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000256 self.offset -= len(buf)
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000257
258 def _read(self, size=1024):
Tim Petersfb0ea522002-11-04 19:50:11 +0000259 if self.fileobj is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000260 raise EOFError("Reached EOF")
Tim Peters07e99cb2001-01-14 23:47:14 +0000261
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000262 if self._new_member:
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000263 # If the _new_member flag is set, we have to
264 # jump to the next member, if there is one.
Tim Peters07e99cb2001-01-14 23:47:14 +0000265 #
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000266 # First, check if we're at the end of the file;
267 # if so, it's time to stop; no more members to read.
268 pos = self.fileobj.tell() # Save current position
269 self.fileobj.seek(0, 2) # Seek to end of file
270 if pos == self.fileobj.tell():
Collin Winterce36ad82007-08-30 01:19:48 +0000271 raise EOFError("Reached EOF")
Tim Peters07e99cb2001-01-14 23:47:14 +0000272 else:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000273 self.fileobj.seek( pos ) # Return to original position
Tim Peters07e99cb2001-01-14 23:47:14 +0000274
275 self._init_read()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000276 self._read_gzip_header()
277 self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000278 self._new_member = False
Tim Peters07e99cb2001-01-14 23:47:14 +0000279
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000280 # Read a chunk of data from the file
281 buf = self.fileobj.read(size)
Tim Peters07e99cb2001-01-14 23:47:14 +0000282
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000283 # If the EOF has been reached, flush the decompression object
284 # and mark this object as finished.
Tim Peters07e99cb2001-01-14 23:47:14 +0000285
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000286 if buf == b"":
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000287 uncompress = self.decompress.flush()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000288 self._read_eof()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000289 self._add_read_data( uncompress )
Collin Winterce36ad82007-08-30 01:19:48 +0000290 raise EOFError('Reached EOF')
Tim Peters07e99cb2001-01-14 23:47:14 +0000291
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000292 uncompress = self.decompress.decompress(buf)
293 self._add_read_data( uncompress )
294
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000295 if self.decompress.unused_data != b"":
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000296 # Ending case: we've come to the end of a member in the file,
297 # so seek back to the start of the unused data, finish up
298 # this member, and read a new gzip header.
299 # (The number of bytes to seek back is the length of the unused
300 # data, minus 8 because _read_eof() will rewind a further 8 bytes)
301 self.fileobj.seek( -len(self.decompress.unused_data)+8, 1)
302
303 # Check the CRC and file size, and set the flag so we read
Tim Peters07e99cb2001-01-14 23:47:14 +0000304 # a new member on the next call
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000305 self._read_eof()
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000306 self._new_member = True
Tim Peters07e99cb2001-01-14 23:47:14 +0000307
308 def _add_read_data(self, data):
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000309 self.crc = zlib.crc32(data, self.crc)
310 self.extrabuf = self.extrabuf + data
311 self.extrasize = self.extrasize + len(data)
312 self.size = self.size + len(data)
Guido van Rossum15262191997-04-30 16:04:57 +0000313
314 def _read_eof(self):
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000315 # We've read to the end of the file, so we have to rewind in order
Tim Peters07e99cb2001-01-14 23:47:14 +0000316 # to reread the 8 bytes containing the CRC and the file size.
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000317 # We check the that the computed CRC and size of the
Tim Peters9288f952002-11-05 20:38:55 +0000318 # uncompressed data matches the stored values. Note that the size
319 # stored is the true file size mod 2**32.
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000320 self.fileobj.seek(-8, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000321 crc32 = read32(self.fileobj)
Tim Petersfb0ea522002-11-04 19:50:11 +0000322 isize = U32(read32(self.fileobj)) # may exceed 2GB
323 if U32(crc32) != U32(self.crc):
Christian Heimese25f35e2008-03-20 10:49:03 +0000324 raise IOError("CRC check failed %s != %s" % (hex(U32(crc32)),
325 hex(U32(self.crc))))
Tim Peters9288f952002-11-05 20:38:55 +0000326 elif isize != LOWU32(self.size):
Collin Winterce36ad82007-08-30 01:19:48 +0000327 raise IOError("Incorrect length of data produced")
Tim Peters07e99cb2001-01-14 23:47:14 +0000328
Guido van Rossum15262191997-04-30 16:04:57 +0000329 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000330 if self.mode == WRITE:
331 self.fileobj.write(self.compress.flush())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000332 # The native zlib crc is an unsigned 32-bit integer, but
333 # the Python wrapper implicitly casts that to a signed C
334 # long. So, on a 32-bit box self.crc may "look negative",
335 # while the same crc on a 64-bit box may "look positive".
336 # To avoid irksome warnings from the `struct` module, force
337 # it to look positive on all boxes.
338 write32u(self.fileobj, LOWU32(self.crc))
Tim Peters9288f952002-11-05 20:38:55 +0000339 # self.size may exceed 2GB, or even 4GB
340 write32u(self.fileobj, LOWU32(self.size))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000341 self.fileobj = None
342 elif self.mode == READ:
343 self.fileobj = None
344 if self.myfileobj:
345 self.myfileobj.close()
346 self.myfileobj = None
Guido van Rossum15262191997-04-30 16:04:57 +0000347
Andrew M. Kuchling916fcc31999-08-10 13:19:30 +0000348 def __del__(self):
Jeremy Hyltone298c302000-05-08 16:59:59 +0000349 try:
350 if (self.myfileobj is None and
351 self.fileobj is None):
352 return
353 except AttributeError:
354 return
355 self.close()
Tim Peters07e99cb2001-01-14 23:47:14 +0000356
Martin v. Löwisf2a8d632005-03-03 08:35:22 +0000357 def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
358 if self.mode == WRITE:
Tim Peterseba28be2005-03-28 01:08:02 +0000359 # Ensure the compressor's buffer is flushed
360 self.fileobj.write(self.compress.flush(zlib_mode))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000361 self.fileobj.flush()
Guido van Rossum15262191997-04-30 16:04:57 +0000362
Tim Peters5cfb05e2004-07-27 21:02:02 +0000363 def fileno(self):
364 """Invoke the underlying file object's fileno() method.
365
366 This will raise AttributeError if the underlying file object
367 doesn't support fileno().
368 """
369 return self.fileobj.fileno()
370
Guido van Rossum15262191997-04-30 16:04:57 +0000371 def isatty(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000372 return False
Guido van Rossum15262191997-04-30 16:04:57 +0000373
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000374 def tell(self):
375 return self.offset
376
377 def rewind(self):
378 '''Return the uncompressed stream file position indicator to the
Tim Petersab9ba272001-08-09 21:40:30 +0000379 beginning of the file'''
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000380 if self.mode != READ:
381 raise IOError("Can't rewind in write mode")
382 self.fileobj.seek(0)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000383 self._new_member = True
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000384 self.extrabuf = b""
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000385 self.extrasize = 0
386 self.offset = 0
387
Thomas Wouters89f507f2006-12-13 04:49:30 +0000388 def seek(self, offset, whence=0):
389 if whence:
390 if whence == 1:
391 offset = self.offset + offset
392 else:
393 raise ValueError('Seek from end not supported')
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000394 if self.mode == WRITE:
395 if offset < self.offset:
396 raise IOError('Negative seek in write mode')
397 count = offset - self.offset
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000398 chunk = bytes(1024)
Tim Petersfb0ea522002-11-04 19:50:11 +0000399 for i in range(count // 1024):
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000400 self.write(chunk)
401 self.write(bytes(count % 1024))
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000402 elif self.mode == READ:
403 if offset < self.offset:
404 # for negative seek, rewind and do positive seek
405 self.rewind()
406 count = offset - self.offset
Tim Petersfb0ea522002-11-04 19:50:11 +0000407 for i in range(count // 1024):
408 self.read(1024)
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000409 self.read(count % 1024)
410
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000411 def readline(self, size=-1):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000412 if size < 0:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000413 size = sys.maxsize
Thomas Wouters477c8d52006-05-27 19:21:47 +0000414 readsize = self.min_readsize
415 else:
416 readsize = size
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000417 bufs = []
Thomas Wouters477c8d52006-05-27 19:21:47 +0000418 while size != 0:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000419 c = self.read(readsize)
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000420 i = c.find(b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000421
422 # We set i=size to break out of the loop under two
423 # conditions: 1) there's no newline, and the chunk is
424 # larger than size, or 2) there is a newline, but the
425 # resulting line would be longer than 'size'.
426 if (size <= i) or (i == -1 and len(c) > size):
427 i = size - 1
Guido van Rossum15262191997-04-30 16:04:57 +0000428
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000429 if i >= 0 or c == b'':
Thomas Wouters477c8d52006-05-27 19:21:47 +0000430 bufs.append(c[:i + 1]) # Add portion of last chunk
431 self._unread(c[i + 1:]) # Push back rest of chunk
432 break
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000433
434 # Append chunk to list, decrease 'size',
435 bufs.append(c)
436 size = size - len(c)
437 readsize = min(size, readsize * 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000438 if readsize > self.min_readsize:
439 self.min_readsize = min(readsize, self.min_readsize * 2, 512)
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000440 return b''.join(bufs) # Return resulting line
Tim Peters07e99cb2001-01-14 23:47:14 +0000441
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000442 def readlines(self, sizehint=0):
443 # Negative numbers result in reading all the lines
Tim Petersfb0ea522002-11-04 19:50:11 +0000444 if sizehint <= 0:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000445 sizehint = sys.maxsize
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000446 L = []
447 while sizehint > 0:
448 line = self.readline()
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000449 if line == b"":
Tim Petersfb0ea522002-11-04 19:50:11 +0000450 break
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000451 L.append(line)
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000452 sizehint = sizehint - len(line)
453
454 return L
Guido van Rossum15262191997-04-30 16:04:57 +0000455
Guido van Rossum68de3791997-07-19 20:22:23 +0000456 def writelines(self, L):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000457 for line in L:
458 self.write(line)
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000459
Neil Schemenauercacbdf62002-03-20 18:36:00 +0000460 def __iter__(self):
461 return self
462
Georg Brandla18af4e2007-04-21 15:47:16 +0000463 def __next__(self):
Neil Schemenauercacbdf62002-03-20 18:36:00 +0000464 line = self.readline()
465 if line:
466 return line
467 else:
468 raise StopIteration
469
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000470
471def _test():
472 # Act like gzip; with -d, act like gunzip.
473 # The input file is not deleted, however, nor are any other gzip
474 # options or features supported.
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000475 args = sys.argv[1:]
476 decompress = args and args[0] == "-d"
477 if decompress:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000478 args = args[1:]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000479 if not args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000480 args = ["-"]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000481 for arg in args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000482 if decompress:
483 if arg == "-":
484 f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
485 g = sys.stdout
486 else:
487 if arg[-3:] != ".gz":
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000488 print("filename doesn't end in .gz:", repr(arg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000489 continue
490 f = open(arg, "rb")
Georg Brandl1a3284e2007-12-02 09:40:06 +0000491 g = builtins.open(arg[:-3], "wb")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000492 else:
493 if arg == "-":
494 f = sys.stdin
495 g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
496 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000497 f = builtins.open(arg, "rb")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000498 g = open(arg + ".gz", "wb")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000499 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000500 chunk = f.read(1024)
501 if not chunk:
502 break
503 g.write(chunk)
504 if g is not sys.stdout:
505 g.close()
506 if f is not sys.stdin:
507 f.close()
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000508
509if __name__ == '__main__':
510 _test()