/Lib/gzip.py

http://unladen-swallow.googlecode.com/ · Python · 484 lines · 426 code · 23 blank · 35 comment · 31 complexity · 42aa5eaa9e4daba0608bb55041924d91 MD5 · raw file

  1. """Functions that read and write gzipped files.
  2. The user of the file doesn't have to worry about the compression,
  3. but random access is not allowed."""
  4. # based on Andrew Kuchling's minigzip.py distributed with the zlib module
  5. import struct, sys, time
  6. import zlib
  7. import __builtin__
  8. __all__ = ["GzipFile","open"]
  9. FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
  10. READ, WRITE = 1, 2
  11. def write32u(output, value):
  12. # The L format writes the bit pattern correctly whether signed
  13. # or unsigned.
  14. output.write(struct.pack("<L", value))
  15. def read32(input):
  16. return struct.unpack("<I", input.read(4))[0]
  17. def open(filename, mode="rb", compresslevel=9):
  18. """Shorthand for GzipFile(filename, mode, compresslevel).
  19. The filename argument is required; mode defaults to 'rb'
  20. and compresslevel defaults to 9.
  21. """
  22. return GzipFile(filename, mode, compresslevel)
  23. class GzipFile:
  24. """The GzipFile class simulates most of the methods of a file object with
  25. the exception of the readinto() and truncate() methods.
  26. """
  27. myfileobj = None
  28. max_read_chunk = 10 * 1024 * 1024 # 10Mb
  29. def __init__(self, filename=None, mode=None,
  30. compresslevel=9, fileobj=None):
  31. """Constructor for the GzipFile class.
  32. At least one of fileobj and filename must be given a
  33. non-trivial value.
  34. The new class instance is based on fileobj, which can be a regular
  35. file, a StringIO object, or any other object which simulates a file.
  36. It defaults to None, in which case filename is opened to provide
  37. a file object.
  38. When fileobj is not None, the filename argument is only used to be
  39. included in the gzip file header, which may includes the original
  40. filename of the uncompressed file. It defaults to the filename of
  41. fileobj, if discernible; otherwise, it defaults to the empty string,
  42. and in this case the original filename is not included in the header.
  43. The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb',
  44. depending on whether the file will be read or written. The default
  45. is the mode of fileobj if discernible; otherwise, the default is 'rb'.
  46. Be aware that only the 'rb', 'ab', and 'wb' values should be used
  47. for cross-platform portability.
  48. The compresslevel argument is an integer from 1 to 9 controlling the
  49. level of compression; 1 is fastest and produces the least compression,
  50. and 9 is slowest and produces the most compression. The default is 9.
  51. """
  52. # guarantee the file is opened in binary mode on platforms
  53. # that care about that sort of thing
  54. if mode and 'b' not in mode:
  55. mode += 'b'
  56. if fileobj is None:
  57. fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
  58. if filename is None:
  59. if hasattr(fileobj, 'name'): filename = fileobj.name
  60. else: filename = ''
  61. if mode is None:
  62. if hasattr(fileobj, 'mode'): mode = fileobj.mode
  63. else: mode = 'rb'
  64. if mode[0:1] == 'r':
  65. self.mode = READ
  66. # Set flag indicating start of a new member
  67. self._new_member = True
  68. self.extrabuf = ""
  69. self.extrasize = 0
  70. self.name = filename
  71. # Starts small, scales exponentially
  72. self.min_readsize = 100
  73. elif mode[0:1] == 'w' or mode[0:1] == 'a':
  74. self.mode = WRITE
  75. self._init_write(filename)
  76. self.compress = zlib.compressobj(compresslevel,
  77. zlib.DEFLATED,
  78. -zlib.MAX_WBITS,
  79. zlib.DEF_MEM_LEVEL,
  80. 0)
  81. else:
  82. raise IOError, "Mode " + mode + " not supported"
  83. self.fileobj = fileobj
  84. self.offset = 0
  85. if self.mode == WRITE:
  86. self._write_gzip_header()
  87. @property
  88. def filename(self):
  89. import warnings
  90. warnings.warn("use the name attribute", DeprecationWarning, 2)
  91. if self.mode == WRITE and self.name[-3:] != ".gz":
  92. return self.name + ".gz"
  93. return self.name
  94. def __repr__(self):
  95. s = repr(self.fileobj)
  96. return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
  97. def _init_write(self, filename):
  98. self.name = filename
  99. self.crc = zlib.crc32("") & 0xffffffffL
  100. self.size = 0
  101. self.writebuf = []
  102. self.bufsize = 0
  103. def _write_gzip_header(self):
  104. self.fileobj.write('\037\213') # magic header
  105. self.fileobj.write('\010') # compression method
  106. fname = self.name
  107. if fname.endswith(".gz"):
  108. fname = fname[:-3]
  109. flags = 0
  110. if fname:
  111. flags = FNAME
  112. self.fileobj.write(chr(flags))
  113. write32u(self.fileobj, long(time.time()))
  114. self.fileobj.write('\002')
  115. self.fileobj.write('\377')
  116. if fname:
  117. self.fileobj.write(fname + '\000')
  118. def _init_read(self):
  119. self.crc = zlib.crc32("") & 0xffffffffL
  120. self.size = 0
  121. def _read_gzip_header(self):
  122. magic = self.fileobj.read(2)
  123. if magic != '\037\213':
  124. raise IOError, 'Not a gzipped file'
  125. method = ord( self.fileobj.read(1) )
  126. if method != 8:
  127. raise IOError, 'Unknown compression method'
  128. flag = ord( self.fileobj.read(1) )
  129. # modtime = self.fileobj.read(4)
  130. # extraflag = self.fileobj.read(1)
  131. # os = self.fileobj.read(1)
  132. self.fileobj.read(6)
  133. if flag & FEXTRA:
  134. # Read & discard the extra field, if present
  135. xlen = ord(self.fileobj.read(1))
  136. xlen = xlen + 256*ord(self.fileobj.read(1))
  137. self.fileobj.read(xlen)
  138. if flag & FNAME:
  139. # Read and discard a null-terminated string containing the filename
  140. while True:
  141. s = self.fileobj.read(1)
  142. if not s or s=='\000':
  143. break
  144. if flag & FCOMMENT:
  145. # Read and discard a null-terminated string containing a comment
  146. while True:
  147. s = self.fileobj.read(1)
  148. if not s or s=='\000':
  149. break
  150. if flag & FHCRC:
  151. self.fileobj.read(2) # Read & discard the 16-bit header CRC
  152. def write(self,data):
  153. if self.mode != WRITE:
  154. import errno
  155. raise IOError(errno.EBADF, "write() on read-only GzipFile object")
  156. if self.fileobj is None:
  157. raise ValueError, "write() on closed GzipFile object"
  158. if len(data) > 0:
  159. self.size = self.size + len(data)
  160. self.crc = zlib.crc32(data, self.crc) & 0xffffffffL
  161. self.fileobj.write( self.compress.compress(data) )
  162. self.offset += len(data)
  163. def read(self, size=-1):
  164. if self.mode != READ:
  165. import errno
  166. raise IOError(errno.EBADF, "read() on write-only GzipFile object")
  167. if self.extrasize <= 0 and self.fileobj is None:
  168. return ''
  169. readsize = 1024
  170. if size < 0: # get the whole thing
  171. try:
  172. while True:
  173. self._read(readsize)
  174. readsize = min(self.max_read_chunk, readsize * 2)
  175. except EOFError:
  176. size = self.extrasize
  177. else: # just get some more of it
  178. try:
  179. while size > self.extrasize:
  180. self._read(readsize)
  181. readsize = min(self.max_read_chunk, readsize * 2)
  182. except EOFError:
  183. if size > self.extrasize:
  184. size = self.extrasize
  185. chunk = self.extrabuf[:size]
  186. self.extrabuf = self.extrabuf[size:]
  187. self.extrasize = self.extrasize - size
  188. self.offset += size
  189. return chunk
  190. def _unread(self, buf):
  191. self.extrabuf = buf + self.extrabuf
  192. self.extrasize = len(buf) + self.extrasize
  193. self.offset -= len(buf)
  194. def _read(self, size=1024):
  195. if self.fileobj is None:
  196. raise EOFError, "Reached EOF"
  197. if self._new_member:
  198. # If the _new_member flag is set, we have to
  199. # jump to the next member, if there is one.
  200. #
  201. # First, check if we're at the end of the file;
  202. # if so, it's time to stop; no more members to read.
  203. pos = self.fileobj.tell() # Save current position
  204. self.fileobj.seek(0, 2) # Seek to end of file
  205. if pos == self.fileobj.tell():
  206. raise EOFError, "Reached EOF"
  207. else:
  208. self.fileobj.seek( pos ) # Return to original position
  209. self._init_read()
  210. self._read_gzip_header()
  211. self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
  212. self._new_member = False
  213. # Read a chunk of data from the file
  214. buf = self.fileobj.read(size)
  215. # If the EOF has been reached, flush the decompression object
  216. # and mark this object as finished.
  217. if buf == "":
  218. uncompress = self.decompress.flush()
  219. self._read_eof()
  220. self._add_read_data( uncompress )
  221. raise EOFError, 'Reached EOF'
  222. uncompress = self.decompress.decompress(buf)
  223. self._add_read_data( uncompress )
  224. if self.decompress.unused_data != "":
  225. # Ending case: we've come to the end of a member in the file,
  226. # so seek back to the start of the unused data, finish up
  227. # this member, and read a new gzip header.
  228. # (The number of bytes to seek back is the length of the unused
  229. # data, minus 8 because _read_eof() will rewind a further 8 bytes)
  230. self.fileobj.seek( -len(self.decompress.unused_data)+8, 1)
  231. # Check the CRC and file size, and set the flag so we read
  232. # a new member on the next call
  233. self._read_eof()
  234. self._new_member = True
  235. def _add_read_data(self, data):
  236. self.crc = zlib.crc32(data, self.crc) & 0xffffffffL
  237. self.extrabuf = self.extrabuf + data
  238. self.extrasize = self.extrasize + len(data)
  239. self.size = self.size + len(data)
  240. def _read_eof(self):
  241. # We've read to the end of the file, so we have to rewind in order
  242. # to reread the 8 bytes containing the CRC and the file size.
  243. # We check the that the computed CRC and size of the
  244. # uncompressed data matches the stored values. Note that the size
  245. # stored is the true file size mod 2**32.
  246. self.fileobj.seek(-8, 1)
  247. crc32 = read32(self.fileobj)
  248. isize = read32(self.fileobj) # may exceed 2GB
  249. if crc32 != self.crc:
  250. raise IOError("CRC check failed %s != %s" % (hex(crc32),
  251. hex(self.crc)))
  252. elif isize != (self.size & 0xffffffffL):
  253. raise IOError, "Incorrect length of data produced"
  254. def close(self):
  255. if self.fileobj is None:
  256. return
  257. if self.mode == WRITE:
  258. self.fileobj.write(self.compress.flush())
  259. write32u(self.fileobj, self.crc)
  260. # self.size may exceed 2GB, or even 4GB
  261. write32u(self.fileobj, self.size & 0xffffffffL)
  262. self.fileobj = None
  263. elif self.mode == READ:
  264. self.fileobj = None
  265. if self.myfileobj:
  266. self.myfileobj.close()
  267. self.myfileobj = None
  268. def __del__(self):
  269. try:
  270. if (self.myfileobj is None and
  271. self.fileobj is None):
  272. return
  273. except AttributeError:
  274. return
  275. self.close()
  276. def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
  277. if self.mode == WRITE:
  278. # Ensure the compressor's buffer is flushed
  279. self.fileobj.write(self.compress.flush(zlib_mode))
  280. self.fileobj.flush()
  281. def fileno(self):
  282. """Invoke the underlying file object's fileno() method.
  283. This will raise AttributeError if the underlying file object
  284. doesn't support fileno().
  285. """
  286. return self.fileobj.fileno()
  287. def isatty(self):
  288. return False
  289. def tell(self):
  290. return self.offset
  291. def rewind(self):
  292. '''Return the uncompressed stream file position indicator to the
  293. beginning of the file'''
  294. if self.mode != READ:
  295. raise IOError("Can't rewind in write mode")
  296. self.fileobj.seek(0)
  297. self._new_member = True
  298. self.extrabuf = ""
  299. self.extrasize = 0
  300. self.offset = 0
  301. def seek(self, offset, whence=0):
  302. if whence:
  303. if whence == 1:
  304. offset = self.offset + offset
  305. else:
  306. raise ValueError('Seek from end not supported')
  307. if self.mode == WRITE:
  308. if offset < self.offset:
  309. raise IOError('Negative seek in write mode')
  310. count = offset - self.offset
  311. for i in range(count // 1024):
  312. self.write(1024 * '\0')
  313. self.write((count % 1024) * '\0')
  314. elif self.mode == READ:
  315. if offset < self.offset:
  316. # for negative seek, rewind and do positive seek
  317. self.rewind()
  318. count = offset - self.offset
  319. for i in range(count // 1024):
  320. self.read(1024)
  321. self.read(count % 1024)
  322. def readline(self, size=-1):
  323. if size < 0:
  324. size = sys.maxint
  325. readsize = self.min_readsize
  326. else:
  327. readsize = size
  328. bufs = []
  329. while size != 0:
  330. c = self.read(readsize)
  331. i = c.find('\n')
  332. # We set i=size to break out of the loop under two
  333. # conditions: 1) there's no newline, and the chunk is
  334. # larger than size, or 2) there is a newline, but the
  335. # resulting line would be longer than 'size'.
  336. if (size <= i) or (i == -1 and len(c) > size):
  337. i = size - 1
  338. if i >= 0 or c == '':
  339. bufs.append(c[:i + 1]) # Add portion of last chunk
  340. self._unread(c[i + 1:]) # Push back rest of chunk
  341. break
  342. # Append chunk to list, decrease 'size',
  343. bufs.append(c)
  344. size = size - len(c)
  345. readsize = min(size, readsize * 2)
  346. if readsize > self.min_readsize:
  347. self.min_readsize = min(readsize, self.min_readsize * 2, 512)
  348. return ''.join(bufs) # Return resulting line
  349. def readlines(self, sizehint=0):
  350. # Negative numbers result in reading all the lines
  351. if sizehint <= 0:
  352. sizehint = sys.maxint
  353. L = []
  354. while sizehint > 0:
  355. line = self.readline()
  356. if line == "":
  357. break
  358. L.append(line)
  359. sizehint = sizehint - len(line)
  360. return L
  361. def writelines(self, L):
  362. for line in L:
  363. self.write(line)
  364. def __iter__(self):
  365. return self
  366. def next(self):
  367. line = self.readline()
  368. if line:
  369. return line
  370. else:
  371. raise StopIteration
  372. def _test():
  373. # Act like gzip; with -d, act like gunzip.
  374. # The input file is not deleted, however, nor are any other gzip
  375. # options or features supported.
  376. args = sys.argv[1:]
  377. decompress = args and args[0] == "-d"
  378. if decompress:
  379. args = args[1:]
  380. if not args:
  381. args = ["-"]
  382. for arg in args:
  383. if decompress:
  384. if arg == "-":
  385. f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
  386. g = sys.stdout
  387. else:
  388. if arg[-3:] != ".gz":
  389. print "filename doesn't end in .gz:", repr(arg)
  390. continue
  391. f = open(arg, "rb")
  392. g = __builtin__.open(arg[:-3], "wb")
  393. else:
  394. if arg == "-":
  395. f = sys.stdin
  396. g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
  397. else:
  398. f = __builtin__.open(arg, "rb")
  399. g = open(arg + ".gz", "wb")
  400. while True:
  401. chunk = f.read(1024)
  402. if not chunk:
  403. break
  404. g.write(chunk)
  405. if g is not sys.stdout:
  406. g.close()
  407. if f is not sys.stdin:
  408. f.close()
  409. if __name__ == '__main__':
  410. _test()