blob: eeef3f8b908ef228eaa2328d68805371180c0cc8 [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,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000045 compresslevel=9, fileobj=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
72 """
73
Skip Montanaro12424bc2002-05-23 01:43:05 +000074 # guarantee the file is opened in binary mode on platforms
75 # that care about that sort of thing
76 if mode and 'b' not in mode:
77 mode += 'b'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000078 if fileobj is None:
Fred Drake9bb76d11999-04-05 18:33:40 +000079 fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
Guido van Rossum68de3791997-07-19 20:22:23 +000080 if filename is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000081 if hasattr(fileobj, 'name'): filename = fileobj.name
82 else: filename = ''
Guido van Rossum68de3791997-07-19 20:22:23 +000083 if mode is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000084 if hasattr(fileobj, 'mode'): mode = fileobj.mode
Fred Drake9bb76d11999-04-05 18:33:40 +000085 else: mode = 'rb'
Guido van Rossum68de3791997-07-19 20:22:23 +000086
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000087 if mode[0:1] == 'r':
88 self.mode = READ
Tim Peters07e99cb2001-01-14 23:47:14 +000089 # Set flag indicating start of a new member
Guido van Rossum8ca162f2002-04-07 06:36:23 +000090 self._new_member = True
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +000091 self.extrabuf = ""
92 self.extrasize = 0
Lars Gustäbel5b1a7852007-02-13 16:09:24 +000093 self.name = filename
Bob Ippolitod82c3102006-05-22 15:59:12 +000094 # Starts small, scales exponentially
95 self.min_readsize = 100
Guido van Rossum15262191997-04-30 16:04:57 +000096
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +000097 elif mode[0:1] == 'w' or mode[0:1] == 'a':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000098 self.mode = WRITE
99 self._init_write(filename)
100 self.compress = zlib.compressobj(compresslevel,
Tim Peters07e99cb2001-01-14 23:47:14 +0000101 zlib.DEFLATED,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000102 -zlib.MAX_WBITS,
103 zlib.DEF_MEM_LEVEL,
104 0)
105 else:
Martin v. Löwisdb044892002-03-11 06:46:52 +0000106 raise IOError, "Mode " + mode + " not supported"
Guido van Rossum15262191997-04-30 16:04:57 +0000107
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000108 self.fileobj = fileobj
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000109 self.offset = 0
Guido van Rossum15262191997-04-30 16:04:57 +0000110
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 if self.mode == WRITE:
112 self._write_gzip_header()
Guido van Rossum15262191997-04-30 16:04:57 +0000113
Lars Gustäbel5b1a7852007-02-13 16:09:24 +0000114 @property
115 def filename(self):
116 import warnings
117 warnings.warn("use the name attribute", DeprecationWarning)
118 if self.mode == WRITE and self.name[-3:] != ".gz":
119 return self.name + ".gz"
120 return self.name
121
Guido van Rossum15262191997-04-30 16:04:57 +0000122 def __repr__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000123 s = repr(self.fileobj)
124 return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
Guido van Rossum15262191997-04-30 16:04:57 +0000125
126 def _init_write(self, filename):
Lars Gustäbel5b1a7852007-02-13 16:09:24 +0000127 self.name = filename
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000128 self.crc = zlib.crc32("") & 0xffffffffL
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000129 self.size = 0
130 self.writebuf = []
131 self.bufsize = 0
Guido van Rossum15262191997-04-30 16:04:57 +0000132
133 def _write_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000134 self.fileobj.write('\037\213') # magic header
135 self.fileobj.write('\010') # compression method
Lars Gustäbelf19c1b52007-02-13 16:24:00 +0000136 fname = self.name
137 if fname.endswith(".gz"):
138 fname = fname[:-3]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 flags = 0
Lars Gustäbelf19c1b52007-02-13 16:24:00 +0000140 if fname:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000141 flags = FNAME
142 self.fileobj.write(chr(flags))
Guido van Rossum95bdd0b1999-04-12 14:34:16 +0000143 write32u(self.fileobj, long(time.time()))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 self.fileobj.write('\002')
145 self.fileobj.write('\377')
Lars Gustäbelf19c1b52007-02-13 16:24:00 +0000146 if fname:
147 self.fileobj.write(fname + '\000')
Guido van Rossum15262191997-04-30 16:04:57 +0000148
149 def _init_read(self):
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000150 self.crc = zlib.crc32("") & 0xffffffffL
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000151 self.size = 0
Guido van Rossum15262191997-04-30 16:04:57 +0000152
153 def _read_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000154 magic = self.fileobj.read(2)
155 if magic != '\037\213':
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000156 raise IOError, 'Not a gzipped file'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000157 method = ord( self.fileobj.read(1) )
158 if method != 8:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000159 raise IOError, 'Unknown compression method'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000160 flag = ord( self.fileobj.read(1) )
161 # modtime = self.fileobj.read(4)
162 # extraflag = self.fileobj.read(1)
163 # os = self.fileobj.read(1)
164 self.fileobj.read(6)
Guido van Rossum15262191997-04-30 16:04:57 +0000165
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 if flag & FEXTRA:
167 # Read & discard the extra field, if present
Tim Petersfb0ea522002-11-04 19:50:11 +0000168 xlen = ord(self.fileobj.read(1))
169 xlen = xlen + 256*ord(self.fileobj.read(1))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 self.fileobj.read(xlen)
171 if flag & FNAME:
172 # Read and discard a null-terminated string containing the filename
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000173 while True:
Tim Petersfb0ea522002-11-04 19:50:11 +0000174 s = self.fileobj.read(1)
175 if not s or s=='\000':
176 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000177 if flag & FCOMMENT:
178 # Read and discard a null-terminated string containing a comment
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000179 while True:
Tim Petersfb0ea522002-11-04 19:50:11 +0000180 s = self.fileobj.read(1)
181 if not s or s=='\000':
182 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000183 if flag & FHCRC:
184 self.fileobj.read(2) # Read & discard the 16-bit header CRC
Guido van Rossum15262191997-04-30 16:04:57 +0000185
186
187 def write(self,data):
Martin v. Löwisdb044892002-03-11 06:46:52 +0000188 if self.mode != WRITE:
189 import errno
190 raise IOError(errno.EBADF, "write() on read-only GzipFile object")
Tim Peters863ac442002-04-16 01:38:40 +0000191
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000192 if self.fileobj is None:
193 raise ValueError, "write() on closed GzipFile object"
194 if len(data) > 0:
195 self.size = self.size + len(data)
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000196 self.crc = zlib.crc32(data, self.crc) & 0xffffffffL
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000197 self.fileobj.write( self.compress.compress(data) )
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000198 self.offset += len(data)
Guido van Rossum15262191997-04-30 16:04:57 +0000199
Guido van Rossum56068012000-02-02 16:51:06 +0000200 def read(self, size=-1):
Martin v. Löwisdb044892002-03-11 06:46:52 +0000201 if self.mode != READ:
202 import errno
Brett Cannonedfb3022003-12-04 19:28:06 +0000203 raise IOError(errno.EBADF, "read() on write-only GzipFile object")
Tim Peters863ac442002-04-16 01:38:40 +0000204
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000205 if self.extrasize <= 0 and self.fileobj is None:
206 return ''
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000207
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000208 readsize = 1024
Guido van Rossum56068012000-02-02 16:51:06 +0000209 if size < 0: # get the whole thing
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000210 try:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000211 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000212 self._read(readsize)
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000213 readsize = min(self.max_read_chunk, readsize * 2)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000214 except EOFError:
215 size = self.extrasize
216 else: # just get some more of it
217 try:
218 while size > self.extrasize:
219 self._read(readsize)
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000220 readsize = min(self.max_read_chunk, readsize * 2)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 except EOFError:
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000222 if size > self.extrasize:
223 size = self.extrasize
Tim Peters07e99cb2001-01-14 23:47:14 +0000224
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000225 chunk = self.extrabuf[:size]
226 self.extrabuf = self.extrabuf[size:]
227 self.extrasize = self.extrasize - size
Guido van Rossum15262191997-04-30 16:04:57 +0000228
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000229 self.offset += size
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 return chunk
Guido van Rossum15262191997-04-30 16:04:57 +0000231
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000232 def _unread(self, buf):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000233 self.extrabuf = buf + self.extrabuf
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000234 self.extrasize = len(buf) + self.extrasize
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000235 self.offset -= len(buf)
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000236
237 def _read(self, size=1024):
Tim Petersfb0ea522002-11-04 19:50:11 +0000238 if self.fileobj is None:
239 raise EOFError, "Reached EOF"
Tim Peters07e99cb2001-01-14 23:47:14 +0000240
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000241 if self._new_member:
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000242 # If the _new_member flag is set, we have to
243 # jump to the next member, if there is one.
Tim Peters07e99cb2001-01-14 23:47:14 +0000244 #
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000245 # First, check if we're at the end of the file;
246 # if so, it's time to stop; no more members to read.
247 pos = self.fileobj.tell() # Save current position
248 self.fileobj.seek(0, 2) # Seek to end of file
249 if pos == self.fileobj.tell():
Andrew M. Kuchling2d813e51999-09-06 16:34:51 +0000250 raise EOFError, "Reached EOF"
Tim Peters07e99cb2001-01-14 23:47:14 +0000251 else:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000252 self.fileobj.seek( pos ) # Return to original position
Tim Peters07e99cb2001-01-14 23:47:14 +0000253
254 self._init_read()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000255 self._read_gzip_header()
256 self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000257 self._new_member = False
Tim Peters07e99cb2001-01-14 23:47:14 +0000258
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000259 # Read a chunk of data from the file
260 buf = self.fileobj.read(size)
Tim Peters07e99cb2001-01-14 23:47:14 +0000261
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000262 # If the EOF has been reached, flush the decompression object
263 # and mark this object as finished.
Tim Peters07e99cb2001-01-14 23:47:14 +0000264
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000265 if buf == "":
266 uncompress = self.decompress.flush()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000267 self._read_eof()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000268 self._add_read_data( uncompress )
269 raise EOFError, 'Reached EOF'
Tim Peters07e99cb2001-01-14 23:47:14 +0000270
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000271 uncompress = self.decompress.decompress(buf)
272 self._add_read_data( uncompress )
273
274 if self.decompress.unused_data != "":
275 # Ending case: we've come to the end of a member in the file,
276 # so seek back to the start of the unused data, finish up
277 # this member, and read a new gzip header.
278 # (The number of bytes to seek back is the length of the unused
279 # data, minus 8 because _read_eof() will rewind a further 8 bytes)
280 self.fileobj.seek( -len(self.decompress.unused_data)+8, 1)
281
282 # Check the CRC and file size, and set the flag so we read
Tim Peters07e99cb2001-01-14 23:47:14 +0000283 # a new member on the next call
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000284 self._read_eof()
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000285 self._new_member = True
Tim Peters07e99cb2001-01-14 23:47:14 +0000286
287 def _add_read_data(self, data):
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000288 self.crc = zlib.crc32(data, self.crc) & 0xffffffffL
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000289 self.extrabuf = self.extrabuf + data
290 self.extrasize = self.extrasize + len(data)
291 self.size = self.size + len(data)
Guido van Rossum15262191997-04-30 16:04:57 +0000292
293 def _read_eof(self):
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000294 # We've read to the end of the file, so we have to rewind in order
Tim Peters07e99cb2001-01-14 23:47:14 +0000295 # to reread the 8 bytes containing the CRC and the file size.
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000296 # We check the that the computed CRC and size of the
Tim Peters9288f952002-11-05 20:38:55 +0000297 # uncompressed data matches the stored values. Note that the size
298 # stored is the true file size mod 2**32.
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000299 self.fileobj.seek(-8, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000300 crc32 = read32(self.fileobj)
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000301 isize = read32(self.fileobj) # may exceed 2GB
302 if crc32 != self.crc:
303 raise IOError("CRC check failed %s != %s" % (hex(crc32),
304 hex(self.crc)))
Gregory P. Smithac830e92008-03-23 23:43:02 +0000305 elif isize != (self.size & 0xffffffffL):
Andrew M. Kuchling64edd6a2003-02-05 21:35:07 +0000306 raise IOError, "Incorrect length of data produced"
Tim Peters07e99cb2001-01-14 23:47:14 +0000307
Guido van Rossum15262191997-04-30 16:04:57 +0000308 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000309 if self.mode == WRITE:
310 self.fileobj.write(self.compress.flush())
Gregory P. Smith79b4ba82008-03-23 21:04:43 +0000311 write32u(self.fileobj, self.crc)
Tim Peters9288f952002-11-05 20:38:55 +0000312 # self.size may exceed 2GB, or even 4GB
Gregory P. Smithdd102842008-03-23 23:45:12 +0000313 write32u(self.fileobj, self.size & 0xffffffffL)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000314 self.fileobj = None
315 elif self.mode == READ:
316 self.fileobj = None
317 if self.myfileobj:
318 self.myfileobj.close()
319 self.myfileobj = None
Guido van Rossum15262191997-04-30 16:04:57 +0000320
Andrew M. Kuchling916fcc31999-08-10 13:19:30 +0000321 def __del__(self):
Jeremy Hyltone298c302000-05-08 16:59:59 +0000322 try:
323 if (self.myfileobj is None and
324 self.fileobj is None):
325 return
326 except AttributeError:
327 return
328 self.close()
Tim Peters07e99cb2001-01-14 23:47:14 +0000329
Martin v. Löwisf2a8d632005-03-03 08:35:22 +0000330 def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
331 if self.mode == WRITE:
Tim Peterseba28be2005-03-28 01:08:02 +0000332 # Ensure the compressor's buffer is flushed
333 self.fileobj.write(self.compress.flush(zlib_mode))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000334 self.fileobj.flush()
Guido van Rossum15262191997-04-30 16:04:57 +0000335
Tim Peters5cfb05e2004-07-27 21:02:02 +0000336 def fileno(self):
337 """Invoke the underlying file object's fileno() method.
338
339 This will raise AttributeError if the underlying file object
340 doesn't support fileno().
341 """
342 return self.fileobj.fileno()
343
Guido van Rossum15262191997-04-30 16:04:57 +0000344 def isatty(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000345 return False
Guido van Rossum15262191997-04-30 16:04:57 +0000346
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000347 def tell(self):
348 return self.offset
349
350 def rewind(self):
351 '''Return the uncompressed stream file position indicator to the
Tim Petersab9ba272001-08-09 21:40:30 +0000352 beginning of the file'''
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000353 if self.mode != READ:
354 raise IOError("Can't rewind in write mode")
355 self.fileobj.seek(0)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000356 self._new_member = True
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000357 self.extrabuf = ""
358 self.extrasize = 0
359 self.offset = 0
360
Martin v. Löwis065f0c82006-11-12 10:41:39 +0000361 def seek(self, offset, whence=0):
362 if whence:
363 if whence == 1:
364 offset = self.offset + offset
365 else:
366 raise ValueError('Seek from end not supported')
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000367 if self.mode == WRITE:
368 if offset < self.offset:
369 raise IOError('Negative seek in write mode')
370 count = offset - self.offset
Tim Petersfb0ea522002-11-04 19:50:11 +0000371 for i in range(count // 1024):
372 self.write(1024 * '\0')
373 self.write((count % 1024) * '\0')
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000374 elif self.mode == READ:
375 if offset < self.offset:
376 # for negative seek, rewind and do positive seek
377 self.rewind()
378 count = offset - self.offset
Tim Petersfb0ea522002-11-04 19:50:11 +0000379 for i in range(count // 1024):
380 self.read(1024)
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000381 self.read(count % 1024)
382
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000383 def readline(self, size=-1):
Bob Ippolitod82c3102006-05-22 15:59:12 +0000384 if size < 0:
385 size = sys.maxint
386 readsize = self.min_readsize
387 else:
388 readsize = size
Bob Ippolitob9759732006-05-22 15:22:46 +0000389 bufs = []
Bob Ippolitod82c3102006-05-22 15:59:12 +0000390 while size != 0:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000391 c = self.read(readsize)
Eric S. Raymondee5e61d2001-02-09 09:10:35 +0000392 i = c.find('\n')
Bob Ippolitod82c3102006-05-22 15:59:12 +0000393
394 # We set i=size to break out of the loop under two
395 # conditions: 1) there's no newline, and the chunk is
396 # larger than size, or 2) there is a newline, but the
397 # resulting line would be longer than 'size'.
398 if (size <= i) or (i == -1 and len(c) > size):
399 i = size - 1
Guido van Rossum15262191997-04-30 16:04:57 +0000400
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000401 if i >= 0 or c == '':
Bob Ippolitod82c3102006-05-22 15:59:12 +0000402 bufs.append(c[:i + 1]) # Add portion of last chunk
403 self._unread(c[i + 1:]) # Push back rest of chunk
404 break
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000405
Bob Ippolitob9759732006-05-22 15:22:46 +0000406 # Append chunk to list, decrease 'size',
407 bufs.append(c)
408 size = size - len(c)
409 readsize = min(size, readsize * 2)
Bob Ippolitod82c3102006-05-22 15:59:12 +0000410 if readsize > self.min_readsize:
411 self.min_readsize = min(readsize, self.min_readsize * 2, 512)
412 return ''.join(bufs) # Return resulting line
Tim Peters07e99cb2001-01-14 23:47:14 +0000413
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000414 def readlines(self, sizehint=0):
415 # Negative numbers result in reading all the lines
Tim Petersfb0ea522002-11-04 19:50:11 +0000416 if sizehint <= 0:
417 sizehint = sys.maxint
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000418 L = []
419 while sizehint > 0:
420 line = self.readline()
Tim Petersfb0ea522002-11-04 19:50:11 +0000421 if line == "":
422 break
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000423 L.append(line)
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000424 sizehint = sizehint - len(line)
425
426 return L
Guido van Rossum15262191997-04-30 16:04:57 +0000427
Guido van Rossum68de3791997-07-19 20:22:23 +0000428 def writelines(self, L):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000429 for line in L:
430 self.write(line)
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000431
Neil Schemenauercacbdf62002-03-20 18:36:00 +0000432 def __iter__(self):
433 return self
434
435 def next(self):
436 line = self.readline()
437 if line:
438 return line
439 else:
440 raise StopIteration
441
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000442
443def _test():
444 # Act like gzip; with -d, act like gunzip.
445 # The input file is not deleted, however, nor are any other gzip
446 # options or features supported.
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000447 args = sys.argv[1:]
448 decompress = args and args[0] == "-d"
449 if decompress:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 args = args[1:]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000451 if not args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000452 args = ["-"]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000453 for arg in args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000454 if decompress:
455 if arg == "-":
456 f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
457 g = sys.stdout
458 else:
459 if arg[-3:] != ".gz":
Walter Dörwald70a6b492004-02-12 17:35:32 +0000460 print "filename doesn't end in .gz:", repr(arg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000461 continue
462 f = open(arg, "rb")
463 g = __builtin__.open(arg[:-3], "wb")
464 else:
465 if arg == "-":
466 f = sys.stdin
467 g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
468 else:
469 f = __builtin__.open(arg, "rb")
470 g = open(arg + ".gz", "wb")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000471 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000472 chunk = f.read(1024)
473 if not chunk:
474 break
475 g.write(chunk)
476 if g is not sys.stdout:
477 g.close()
478 if f is not sys.stdin:
479 f.close()
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000480
481if __name__ == '__main__':
482 _test()