blob: f568796f7a786369f178654b0e1a273437d45b50 [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
Guido van Rossum68de3791997-07-19 20:22:23 +000010import __builtin__
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
Guido van Rossum95bdd0b1999-04-12 14:34:16 +000018def write32u(output, value):
Tim Petersfb0ea522002-11-04 19:50:11 +000019 # The L format writes the bit pattern correctly whether signed
20 # or unsigned.
Guido van Rossum95bdd0b1999-04-12 14:34:16 +000021 output.write(struct.pack("<L", value))
22
Guido van Rossum15262191997-04-30 16:04:57 +000023def read32(input):
Gregory P. Smith79b4ba82008-03-23 21:04:43 +000024 return struct.unpack("<I", input.read(4))[0]
Guido van Rossum15262191997-04-30 16:04:57 +000025
Fred Drakefa1591c1999-04-05 18:37:59 +000026def open(filename, mode="rb", compresslevel=9):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000027 """Shorthand for GzipFile(filename, mode, compresslevel).
28
29 The filename argument is required; mode defaults to 'rb'
30 and compresslevel defaults to 9.
31
32 """
Guido van Rossum15262191997-04-30 16:04:57 +000033 return GzipFile(filename, mode, compresslevel)
34
35class GzipFile:
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000036 """The GzipFile class simulates most of the methods of a file object with
Guido van Rossum97c5fcc2002-08-06 17:03:25 +000037 the exception of the readinto() and truncate() methods.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000038
39 """
Guido van Rossum15262191997-04-30 16:04:57 +000040
Guido van Rossum68de3791997-07-19 20:22:23 +000041 myfileobj = None
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +000042 max_read_chunk = 10 * 1024 * 1024 # 10Mb
Guido van Rossum68de3791997-07-19 20:22:23 +000043
Tim Peters07e99cb2001-01-14 23:47:14 +000044 def __init__(self, filename=None, mode=None,
Antoine Pitrouf0d2c3f2009-01-04 21:29:23 +000045 compresslevel=9, fileobj=None, mtime=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000046 """Constructor for the GzipFile class.
47
48 At least one of fileobj and filename must be given a
49 non-trivial value.
50
51 The new class instance is based on fileobj, which can be a regular
52 file, a StringIO object, or any other object which simulates a file.
53 It defaults to None, in which case filename is opened to provide
54 a file object.
55
56 When fileobj is not None, the filename argument is only used to be
57 included in the gzip file header, which may includes the original
58 filename of the uncompressed file. It defaults to the filename of
59 fileobj, if discernible; otherwise, it defaults to the empty string,
60 and in this case the original filename is not included in the header.
61
62 The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb',
63 depending on whether the file will be read or written. The default
64 is the mode of fileobj if discernible; otherwise, the default is 'rb'.
65 Be aware that only the 'rb', 'ab', and 'wb' values should be used
66 for cross-platform portability.
67
68 The compresslevel argument is an integer from 1 to 9 controlling the
69 level of compression; 1 is fastest and produces the least compression,
70 and 9 is slowest and produces the most compression. The default is 9.
71
Antoine Pitrouf0d2c3f2009-01-04 21:29:23 +000072 The mtime argument is an optional numeric timestamp to be written
73 to the stream when compressing. All gzip compressed streams
74 are required to contain a timestamp. If omitted or None, the
75 current time is used. This module ignores the timestamp when
76 decompressing; however, some programs, such as gunzip, make use
77 of it. The format of the timestamp is the same as that of the
78 return value of time.time() and of the st_mtime member of the
79 object returned by os.stat().
80
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000081 """
82
Skip Montanaro12424bc2002-05-23 01:43:05 +000083 # guarantee the file is opened in binary mode on platforms
84 # that care about that sort of thing
85 if mode and 'b' not in mode:
86 mode += 'b'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000087 if fileobj is None:
Fred Drake9bb76d11999-04-05 18:33:40 +000088 fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
Guido van Rossum68de3791997-07-19 20:22:23 +000089 if filename is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000090 if hasattr(fileobj, 'name'): filename = fileobj.name
91 else: filename = ''
Guido van Rossum68de3791997-07-19 20:22:23 +000092 if mode is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000093 if hasattr(fileobj, 'mode'): mode = fileobj.mode
Fred Drake9bb76d11999-04-05 18:33:40 +000094 else: mode = 'rb'
Guido van Rossum68de3791997-07-19 20:22:23 +000095
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000096 if mode[0:1] == 'r':
97 self.mode = READ
Tim Peters07e99cb2001-01-14 23:47:14 +000098 # Set flag indicating start of a new member
Guido van Rossum8ca162f2002-04-07 06:36:23 +000099 self._new_member = True
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000100 self.extrabuf = ""
101 self.extrasize = 0
Lars Gustäbel5b1a7852007-02-13 16:09:24 +0000102 self.name = filename
Bob Ippolitod82c3102006-05-22 15:59:12 +0000103 # Starts small, scales exponentially
104 self.min_readsize = 100
Guido van Rossum15262191997-04-30 16:04:57 +0000105
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000106 elif mode[0:1] == 'w' or mode[0:1] == 'a':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000107 self.mode = WRITE
108 self._init_write(filename)
109 self.compress = zlib.compressobj(compresslevel,
Tim Peters07e99cb2001-01-14 23:47:14 +0000110 zlib.DEFLATED,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 -zlib.MAX_WBITS,
112 zlib.DEF_MEM_LEVEL,
113 0)
114 else:
Martin v. Löwisdb044892002-03-11 06:46:52 +0000115 raise IOError, "Mode " + mode + " not supported"
Guido van Rossum15262191997-04-30 16:04:57 +0000116
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000117 self.fileobj = fileobj
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000118 self.offset = 0
Antoine Pitrouf0d2c3f2009-01-04 21:29:23 +0000119 self.mtime = mtime
Guido van Rossum15262191997-04-30 16:04:57 +0000120
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000121 if self.mode == WRITE:
122 self._write_gzip_header()
Guido van Rossum15262191997-04-30 16:04:57 +0000123
Lars Gustäbel5b1a7852007-02-13 16:09:24 +0000124 @property
125 def filename(self):
126 import warnings
127 warnings.warn("use the name attribute", DeprecationWarning)
128 if self.mode == WRITE and self.name[-3:] != ".gz":
129 return self.name + ".gz"
130 return self.name
131
Guido van Rossum15262191997-04-30 16:04:57 +0000132 def __repr__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000133 s = repr(self.fileobj)
134 return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
Guido van Rossum15262191997-04-30 16:04:57 +0000135
136 def _init_write(self, filename):
Lars Gustäbel5b1a7852007-02-13 16:09:24 +0000137 self.name = filename
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000138 self.crc = zlib.crc32("") & 0xffffffffL
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 self.size = 0
140 self.writebuf = []
141 self.bufsize = 0
Guido van Rossum15262191997-04-30 16:04:57 +0000142
143 def _write_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 self.fileobj.write('\037\213') # magic header
145 self.fileobj.write('\010') # compression method
Lars Gustäbelf19c1b52007-02-13 16:24:00 +0000146 fname = self.name
147 if fname.endswith(".gz"):
148 fname = fname[:-3]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000149 flags = 0
Lars Gustäbelf19c1b52007-02-13 16:24:00 +0000150 if fname:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000151 flags = FNAME
152 self.fileobj.write(chr(flags))
Antoine Pitrouf0d2c3f2009-01-04 21:29:23 +0000153 mtime = self.mtime
154 if mtime is None:
155 mtime = time.time()
156 write32u(self.fileobj, long(mtime))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000157 self.fileobj.write('\002')
158 self.fileobj.write('\377')
Lars Gustäbelf19c1b52007-02-13 16:24:00 +0000159 if fname:
160 self.fileobj.write(fname + '\000')
Guido van Rossum15262191997-04-30 16:04:57 +0000161
162 def _init_read(self):
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000163 self.crc = zlib.crc32("") & 0xffffffffL
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000164 self.size = 0
Guido van Rossum15262191997-04-30 16:04:57 +0000165
166 def _read_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 magic = self.fileobj.read(2)
168 if magic != '\037\213':
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000169 raise IOError, 'Not a gzipped file'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 method = ord( self.fileobj.read(1) )
171 if method != 8:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000172 raise IOError, 'Unknown compression method'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000173 flag = ord( self.fileobj.read(1) )
Antoine Pitrouf0d2c3f2009-01-04 21:29:23 +0000174 self.mtime = read32(self.fileobj)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000175 # extraflag = self.fileobj.read(1)
176 # os = self.fileobj.read(1)
Antoine Pitrouf0d2c3f2009-01-04 21:29:23 +0000177 self.fileobj.read(2)
Guido van Rossum15262191997-04-30 16:04:57 +0000178
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000179 if flag & FEXTRA:
180 # Read & discard the extra field, if present
Tim Petersfb0ea522002-11-04 19:50:11 +0000181 xlen = ord(self.fileobj.read(1))
182 xlen = xlen + 256*ord(self.fileobj.read(1))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000183 self.fileobj.read(xlen)
184 if flag & FNAME:
185 # Read and discard a null-terminated string containing the filename
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000186 while True:
Tim Petersfb0ea522002-11-04 19:50:11 +0000187 s = self.fileobj.read(1)
188 if not s or s=='\000':
189 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000190 if flag & FCOMMENT:
191 # Read and discard a null-terminated string containing a comment
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000192 while True:
Tim Petersfb0ea522002-11-04 19:50:11 +0000193 s = self.fileobj.read(1)
194 if not s or s=='\000':
195 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 if flag & FHCRC:
197 self.fileobj.read(2) # Read & discard the 16-bit header CRC
Guido van Rossum15262191997-04-30 16:04:57 +0000198
199
200 def write(self,data):
Martin v. Löwisdb044892002-03-11 06:46:52 +0000201 if self.mode != WRITE:
202 import errno
203 raise IOError(errno.EBADF, "write() on read-only GzipFile object")
Tim Peters863ac442002-04-16 01:38:40 +0000204
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000205 if self.fileobj is None:
206 raise ValueError, "write() on closed GzipFile object"
207 if len(data) > 0:
208 self.size = self.size + len(data)
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000209 self.crc = zlib.crc32(data, self.crc) & 0xffffffffL
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000210 self.fileobj.write( self.compress.compress(data) )
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000211 self.offset += len(data)
Guido van Rossum15262191997-04-30 16:04:57 +0000212
Guido van Rossum56068012000-02-02 16:51:06 +0000213 def read(self, size=-1):
Martin v. Löwisdb044892002-03-11 06:46:52 +0000214 if self.mode != READ:
215 import errno
Brett Cannonedfb3022003-12-04 19:28:06 +0000216 raise IOError(errno.EBADF, "read() on write-only GzipFile object")
Tim Peters863ac442002-04-16 01:38:40 +0000217
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000218 if self.extrasize <= 0 and self.fileobj is None:
219 return ''
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000220
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 readsize = 1024
Guido van Rossum56068012000-02-02 16:51:06 +0000222 if size < 0: # get the whole thing
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000223 try:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000224 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000225 self._read(readsize)
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000226 readsize = min(self.max_read_chunk, readsize * 2)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000227 except EOFError:
228 size = self.extrasize
229 else: # just get some more of it
230 try:
231 while size > self.extrasize:
232 self._read(readsize)
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000233 readsize = min(self.max_read_chunk, readsize * 2)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000234 except EOFError:
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000235 if size > self.extrasize:
236 size = self.extrasize
Tim Peters07e99cb2001-01-14 23:47:14 +0000237
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000238 chunk = self.extrabuf[:size]
239 self.extrabuf = self.extrabuf[size:]
240 self.extrasize = self.extrasize - size
Guido van Rossum15262191997-04-30 16:04:57 +0000241
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000242 self.offset += size
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000243 return chunk
Guido van Rossum15262191997-04-30 16:04:57 +0000244
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000245 def _unread(self, buf):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 self.extrabuf = buf + self.extrabuf
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000247 self.extrasize = len(buf) + self.extrasize
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000248 self.offset -= len(buf)
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000249
250 def _read(self, size=1024):
Tim Petersfb0ea522002-11-04 19:50:11 +0000251 if self.fileobj is None:
252 raise EOFError, "Reached EOF"
Tim Peters07e99cb2001-01-14 23:47:14 +0000253
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000254 if self._new_member:
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000255 # If the _new_member flag is set, we have to
256 # jump to the next member, if there is one.
Tim Peters07e99cb2001-01-14 23:47:14 +0000257 #
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000258 # First, check if we're at the end of the file;
259 # if so, it's time to stop; no more members to read.
260 pos = self.fileobj.tell() # Save current position
261 self.fileobj.seek(0, 2) # Seek to end of file
262 if pos == self.fileobj.tell():
Andrew M. Kuchling2d813e51999-09-06 16:34:51 +0000263 raise EOFError, "Reached EOF"
Tim Peters07e99cb2001-01-14 23:47:14 +0000264 else:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000265 self.fileobj.seek( pos ) # Return to original position
Tim Peters07e99cb2001-01-14 23:47:14 +0000266
267 self._init_read()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000268 self._read_gzip_header()
269 self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000270 self._new_member = False
Tim Peters07e99cb2001-01-14 23:47:14 +0000271
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000272 # Read a chunk of data from the file
273 buf = self.fileobj.read(size)
Tim Peters07e99cb2001-01-14 23:47:14 +0000274
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000275 # If the EOF has been reached, flush the decompression object
276 # and mark this object as finished.
Tim Peters07e99cb2001-01-14 23:47:14 +0000277
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000278 if buf == "":
279 uncompress = self.decompress.flush()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000280 self._read_eof()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000281 self._add_read_data( uncompress )
282 raise EOFError, 'Reached EOF'
Tim Peters07e99cb2001-01-14 23:47:14 +0000283
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000284 uncompress = self.decompress.decompress(buf)
285 self._add_read_data( uncompress )
286
287 if self.decompress.unused_data != "":
288 # Ending case: we've come to the end of a member in the file,
289 # so seek back to the start of the unused data, finish up
290 # this member, and read a new gzip header.
291 # (The number of bytes to seek back is the length of the unused
292 # data, minus 8 because _read_eof() will rewind a further 8 bytes)
293 self.fileobj.seek( -len(self.decompress.unused_data)+8, 1)
294
295 # Check the CRC and file size, and set the flag so we read
Tim Peters07e99cb2001-01-14 23:47:14 +0000296 # a new member on the next call
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000297 self._read_eof()
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000298 self._new_member = True
Tim Peters07e99cb2001-01-14 23:47:14 +0000299
300 def _add_read_data(self, data):
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000301 self.crc = zlib.crc32(data, self.crc) & 0xffffffffL
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000302 self.extrabuf = self.extrabuf + data
303 self.extrasize = self.extrasize + len(data)
304 self.size = self.size + len(data)
Guido van Rossum15262191997-04-30 16:04:57 +0000305
306 def _read_eof(self):
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000307 # We've read to the end of the file, so we have to rewind in order
Tim Peters07e99cb2001-01-14 23:47:14 +0000308 # to reread the 8 bytes containing the CRC and the file size.
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000309 # We check the that the computed CRC and size of the
Tim Peters9288f952002-11-05 20:38:55 +0000310 # uncompressed data matches the stored values. Note that the size
311 # stored is the true file size mod 2**32.
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000312 self.fileobj.seek(-8, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000313 crc32 = read32(self.fileobj)
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000314 isize = read32(self.fileobj) # may exceed 2GB
315 if crc32 != self.crc:
316 raise IOError("CRC check failed %s != %s" % (hex(crc32),
317 hex(self.crc)))
Gregory P. Smithac830e92008-03-23 23:43:02 +0000318 elif isize != (self.size & 0xffffffffL):
Andrew M. Kuchling64edd6a2003-02-05 21:35:07 +0000319 raise IOError, "Incorrect length of data produced"
Tim Peters07e99cb2001-01-14 23:47:14 +0000320
Guido van Rossum15262191997-04-30 16:04:57 +0000321 def close(self):
Georg Brandle08e3d02008-05-25 08:07:37 +0000322 if self.fileobj is None:
323 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000324 if self.mode == WRITE:
325 self.fileobj.write(self.compress.flush())
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000326 write32u(self.fileobj, self.crc)
Tim Peters9288f952002-11-05 20:38:55 +0000327 # self.size may exceed 2GB, or even 4GB
Gregory P. Smithdd102842008-03-23 23:45:12 +0000328 write32u(self.fileobj, self.size & 0xffffffffL)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000329 self.fileobj = None
330 elif self.mode == READ:
331 self.fileobj = None
332 if self.myfileobj:
333 self.myfileobj.close()
334 self.myfileobj = None
Guido van Rossum15262191997-04-30 16:04:57 +0000335
Andrew M. Kuchling916fcc31999-08-10 13:19:30 +0000336 def __del__(self):
Jeremy Hyltone298c302000-05-08 16:59:59 +0000337 try:
338 if (self.myfileobj is None and
339 self.fileobj is None):
340 return
341 except AttributeError:
342 return
343 self.close()
Tim Peters07e99cb2001-01-14 23:47:14 +0000344
Martin v. Löwisf2a8d632005-03-03 08:35:22 +0000345 def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
346 if self.mode == WRITE:
Tim Peterseba28be2005-03-28 01:08:02 +0000347 # Ensure the compressor's buffer is flushed
348 self.fileobj.write(self.compress.flush(zlib_mode))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000349 self.fileobj.flush()
Guido van Rossum15262191997-04-30 16:04:57 +0000350
Tim Peters5cfb05e2004-07-27 21:02:02 +0000351 def fileno(self):
352 """Invoke the underlying file object's fileno() method.
353
354 This will raise AttributeError if the underlying file object
355 doesn't support fileno().
356 """
357 return self.fileobj.fileno()
358
Guido van Rossum15262191997-04-30 16:04:57 +0000359 def isatty(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000360 return False
Guido van Rossum15262191997-04-30 16:04:57 +0000361
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000362 def tell(self):
363 return self.offset
364
365 def rewind(self):
366 '''Return the uncompressed stream file position indicator to the
Tim Petersab9ba272001-08-09 21:40:30 +0000367 beginning of the file'''
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000368 if self.mode != READ:
369 raise IOError("Can't rewind in write mode")
370 self.fileobj.seek(0)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000371 self._new_member = True
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000372 self.extrabuf = ""
373 self.extrasize = 0
374 self.offset = 0
375
Martin v. Löwis065f0c82006-11-12 10:41:39 +0000376 def seek(self, offset, whence=0):
377 if whence:
378 if whence == 1:
379 offset = self.offset + offset
380 else:
381 raise ValueError('Seek from end not supported')
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000382 if self.mode == WRITE:
383 if offset < self.offset:
384 raise IOError('Negative seek in write mode')
385 count = offset - self.offset
Tim Petersfb0ea522002-11-04 19:50:11 +0000386 for i in range(count // 1024):
387 self.write(1024 * '\0')
388 self.write((count % 1024) * '\0')
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000389 elif self.mode == READ:
390 if offset < self.offset:
391 # for negative seek, rewind and do positive seek
392 self.rewind()
393 count = offset - self.offset
Tim Petersfb0ea522002-11-04 19:50:11 +0000394 for i in range(count // 1024):
395 self.read(1024)
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000396 self.read(count % 1024)
397
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000398 def readline(self, size=-1):
Bob Ippolitod82c3102006-05-22 15:59:12 +0000399 if size < 0:
400 size = sys.maxint
401 readsize = self.min_readsize
402 else:
403 readsize = size
Bob Ippolitob9759732006-05-22 15:22:46 +0000404 bufs = []
Bob Ippolitod82c3102006-05-22 15:59:12 +0000405 while size != 0:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 c = self.read(readsize)
Eric S. Raymondee5e61d2001-02-09 09:10:35 +0000407 i = c.find('\n')
Bob Ippolitod82c3102006-05-22 15:59:12 +0000408
409 # We set i=size to break out of the loop under two
410 # conditions: 1) there's no newline, and the chunk is
411 # larger than size, or 2) there is a newline, but the
412 # resulting line would be longer than 'size'.
413 if (size <= i) or (i == -1 and len(c) > size):
414 i = size - 1
Guido van Rossum15262191997-04-30 16:04:57 +0000415
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000416 if i >= 0 or c == '':
Bob Ippolitod82c3102006-05-22 15:59:12 +0000417 bufs.append(c[:i + 1]) # Add portion of last chunk
418 self._unread(c[i + 1:]) # Push back rest of chunk
419 break
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000420
Bob Ippolitob9759732006-05-22 15:22:46 +0000421 # Append chunk to list, decrease 'size',
422 bufs.append(c)
423 size = size - len(c)
424 readsize = min(size, readsize * 2)
Bob Ippolitod82c3102006-05-22 15:59:12 +0000425 if readsize > self.min_readsize:
426 self.min_readsize = min(readsize, self.min_readsize * 2, 512)
427 return ''.join(bufs) # Return resulting line
Tim Peters07e99cb2001-01-14 23:47:14 +0000428
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000429 def readlines(self, sizehint=0):
430 # Negative numbers result in reading all the lines
Tim Petersfb0ea522002-11-04 19:50:11 +0000431 if sizehint <= 0:
432 sizehint = sys.maxint
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000433 L = []
434 while sizehint > 0:
435 line = self.readline()
Tim Petersfb0ea522002-11-04 19:50:11 +0000436 if line == "":
437 break
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000438 L.append(line)
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000439 sizehint = sizehint - len(line)
440
441 return L
Guido van Rossum15262191997-04-30 16:04:57 +0000442
Guido van Rossum68de3791997-07-19 20:22:23 +0000443 def writelines(self, L):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000444 for line in L:
445 self.write(line)
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000446
Neil Schemenauercacbdf62002-03-20 18:36:00 +0000447 def __iter__(self):
448 return self
449
450 def next(self):
451 line = self.readline()
452 if line:
453 return line
454 else:
455 raise StopIteration
456
Antoine Pitroub74fc2b2009-01-10 16:13:45 +0000457 def __enter__(self):
458 if self.fileobj is None:
459 raise ValueError("I/O operation on closed GzipFile object")
460 return self
461
462 def __exit__(self, *args):
463 self.close()
464
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000465
466def _test():
467 # Act like gzip; with -d, act like gunzip.
468 # The input file is not deleted, however, nor are any other gzip
469 # options or features supported.
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000470 args = sys.argv[1:]
471 decompress = args and args[0] == "-d"
472 if decompress:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000473 args = args[1:]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000474 if not args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000475 args = ["-"]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000476 for arg in args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000477 if decompress:
478 if arg == "-":
479 f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
480 g = sys.stdout
481 else:
482 if arg[-3:] != ".gz":
Walter Dörwald70a6b492004-02-12 17:35:32 +0000483 print "filename doesn't end in .gz:", repr(arg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000484 continue
485 f = open(arg, "rb")
486 g = __builtin__.open(arg[:-3], "wb")
487 else:
488 if arg == "-":
489 f = sys.stdin
490 g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
491 else:
492 f = __builtin__.open(arg, "rb")
493 g = open(arg + ".gz", "wb")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000494 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000495 chunk = f.read(1024)
496 if not chunk:
497 break
498 g.write(chunk)
499 if g is not sys.stdout:
500 g.close()
501 if f is not sys.stdin:
502 f.close()
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000503
504if __name__ == '__main__':
505 _test()