bz2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. """Interface to the libbzip2 compression library.
  2. This module provides a file interface, classes for incremental
  3. (de)compression, and functions for one-shot (de)compression.
  4. """
  5. __all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor",
  6. "open", "compress", "decompress"]
  7. __author__ = "Nadeem Vawda <nadeem.vawda@gmail.com>"
  8. from builtins import open as _builtin_open
  9. import io
  10. import os
  11. import warnings
  12. import _compression
  13. from threading import RLock
  14. from _bz2 import BZ2Compressor, BZ2Decompressor
  15. _MODE_CLOSED = 0
  16. _MODE_READ = 1
  17. # Value 2 no longer used
  18. _MODE_WRITE = 3
  19. class BZ2File(_compression.BaseStream):
  20. """A file object providing transparent bzip2 (de)compression.
  21. A BZ2File can act as a wrapper for an existing file object, or refer
  22. directly to a named file on disk.
  23. Note that BZ2File provides a *binary* file interface - data read is
  24. returned as bytes, and data to be written should be given as bytes.
  25. """
  26. def __init__(self, filename, mode="r", buffering=None, compresslevel=9):
  27. """Open a bzip2-compressed file.
  28. If filename is a str, bytes, or PathLike object, it gives the
  29. name of the file to be opened. Otherwise, it should be a file
  30. object, which will be used to read or write the compressed data.
  31. mode can be 'r' for reading (default), 'w' for (over)writing,
  32. 'x' for creating exclusively, or 'a' for appending. These can
  33. equivalently be given as 'rb', 'wb', 'xb', and 'ab'.
  34. buffering is ignored. Its use is deprecated.
  35. If mode is 'w', 'x' or 'a', compresslevel can be a number between 1
  36. and 9 specifying the level of compression: 1 produces the least
  37. compression, and 9 (default) produces the most compression.
  38. If mode is 'r', the input file may be the concatenation of
  39. multiple compressed streams.
  40. """
  41. # This lock must be recursive, so that BufferedIOBase's
  42. # writelines() does not deadlock.
  43. self._lock = RLock()
  44. self._fp = None
  45. self._closefp = False
  46. self._mode = _MODE_CLOSED
  47. if buffering is not None:
  48. warnings.warn("Use of 'buffering' argument is deprecated",
  49. DeprecationWarning)
  50. if not (1 <= compresslevel <= 9):
  51. raise ValueError("compresslevel must be between 1 and 9")
  52. if mode in ("", "r", "rb"):
  53. mode = "rb"
  54. mode_code = _MODE_READ
  55. elif mode in ("w", "wb"):
  56. mode = "wb"
  57. mode_code = _MODE_WRITE
  58. self._compressor = BZ2Compressor(compresslevel)
  59. elif mode in ("x", "xb"):
  60. mode = "xb"
  61. mode_code = _MODE_WRITE
  62. self._compressor = BZ2Compressor(compresslevel)
  63. elif mode in ("a", "ab"):
  64. mode = "ab"
  65. mode_code = _MODE_WRITE
  66. self._compressor = BZ2Compressor(compresslevel)
  67. else:
  68. raise ValueError("Invalid mode: %r" % (mode,))
  69. if isinstance(filename, (str, bytes, os.PathLike)):
  70. self._fp = _builtin_open(filename, mode)
  71. self._closefp = True
  72. self._mode = mode_code
  73. elif hasattr(filename, "read") or hasattr(filename, "write"):
  74. self._fp = filename
  75. self._mode = mode_code
  76. else:
  77. raise TypeError("filename must be a str, bytes, file or PathLike object")
  78. if self._mode == _MODE_READ:
  79. raw = _compression.DecompressReader(self._fp,
  80. BZ2Decompressor, trailing_error=OSError)
  81. self._buffer = io.BufferedReader(raw)
  82. else:
  83. self._pos = 0
  84. def close(self):
  85. """Flush and close the file.
  86. May be called more than once without error. Once the file is
  87. closed, any other operation on it will raise a ValueError.
  88. """
  89. with self._lock:
  90. if self._mode == _MODE_CLOSED:
  91. return
  92. try:
  93. if self._mode == _MODE_READ:
  94. self._buffer.close()
  95. elif self._mode == _MODE_WRITE:
  96. self._fp.write(self._compressor.flush())
  97. self._compressor = None
  98. finally:
  99. try:
  100. if self._closefp:
  101. self._fp.close()
  102. finally:
  103. self._fp = None
  104. self._closefp = False
  105. self._mode = _MODE_CLOSED
  106. self._buffer = None
  107. @property
  108. def closed(self):
  109. """True if this file is closed."""
  110. return self._mode == _MODE_CLOSED
  111. def fileno(self):
  112. """Return the file descriptor for the underlying file."""
  113. self._check_not_closed()
  114. return self._fp.fileno()
  115. def seekable(self):
  116. """Return whether the file supports seeking."""
  117. return self.readable() and self._buffer.seekable()
  118. def readable(self):
  119. """Return whether the file was opened for reading."""
  120. self._check_not_closed()
  121. return self._mode == _MODE_READ
  122. def writable(self):
  123. """Return whether the file was opened for writing."""
  124. self._check_not_closed()
  125. return self._mode == _MODE_WRITE
  126. def peek(self, n=0):
  127. """Return buffered data without advancing the file position.
  128. Always returns at least one byte of data, unless at EOF.
  129. The exact number of bytes returned is unspecified.
  130. """
  131. with self._lock:
  132. self._check_can_read()
  133. # Relies on the undocumented fact that BufferedReader.peek()
  134. # always returns at least one byte (except at EOF), independent
  135. # of the value of n
  136. return self._buffer.peek(n)
  137. def read(self, size=-1):
  138. """Read up to size uncompressed bytes from the file.
  139. If size is negative or omitted, read until EOF is reached.
  140. Returns b'' if the file is already at EOF.
  141. """
  142. with self._lock:
  143. self._check_can_read()
  144. return self._buffer.read(size)
  145. def read1(self, size=-1):
  146. """Read up to size uncompressed bytes, while trying to avoid
  147. making multiple reads from the underlying stream. Reads up to a
  148. buffer's worth of data if size is negative.
  149. Returns b'' if the file is at EOF.
  150. """
  151. with self._lock:
  152. self._check_can_read()
  153. if size < 0:
  154. size = io.DEFAULT_BUFFER_SIZE
  155. return self._buffer.read1(size)
  156. def readinto(self, b):
  157. """Read bytes into b.
  158. Returns the number of bytes read (0 for EOF).
  159. """
  160. with self._lock:
  161. self._check_can_read()
  162. return self._buffer.readinto(b)
  163. def readline(self, size=-1):
  164. """Read a line of uncompressed bytes from the file.
  165. The terminating newline (if present) is retained. If size is
  166. non-negative, no more than size bytes will be read (in which
  167. case the line may be incomplete). Returns b'' if already at EOF.
  168. """
  169. if not isinstance(size, int):
  170. if not hasattr(size, "__index__"):
  171. raise TypeError("Integer argument expected")
  172. size = size.__index__()
  173. with self._lock:
  174. self._check_can_read()
  175. return self._buffer.readline(size)
  176. def readlines(self, size=-1):
  177. """Read a list of lines of uncompressed bytes from the file.
  178. size can be specified to control the number of lines read: no
  179. further lines will be read once the total size of the lines read
  180. so far equals or exceeds size.
  181. """
  182. if not isinstance(size, int):
  183. if not hasattr(size, "__index__"):
  184. raise TypeError("Integer argument expected")
  185. size = size.__index__()
  186. with self._lock:
  187. self._check_can_read()
  188. return self._buffer.readlines(size)
  189. def write(self, data):
  190. """Write a byte string to the file.
  191. Returns the number of uncompressed bytes written, which is
  192. always len(data). Note that due to buffering, the file on disk
  193. may not reflect the data written until close() is called.
  194. """
  195. with self._lock:
  196. self._check_can_write()
  197. compressed = self._compressor.compress(data)
  198. self._fp.write(compressed)
  199. self._pos += len(data)
  200. return len(data)
  201. def writelines(self, seq):
  202. """Write a sequence of byte strings to the file.
  203. Returns the number of uncompressed bytes written.
  204. seq can be any iterable yielding byte strings.
  205. Line separators are not added between the written byte strings.
  206. """
  207. with self._lock:
  208. return _compression.BaseStream.writelines(self, seq)
  209. def seek(self, offset, whence=io.SEEK_SET):
  210. """Change the file position.
  211. The new position is specified by offset, relative to the
  212. position indicated by whence. Values for whence are:
  213. 0: start of stream (default); offset must not be negative
  214. 1: current stream position
  215. 2: end of stream; offset must not be positive
  216. Returns the new file position.
  217. Note that seeking is emulated, so depending on the parameters,
  218. this operation may be extremely slow.
  219. """
  220. with self._lock:
  221. self._check_can_seek()
  222. return self._buffer.seek(offset, whence)
  223. def tell(self):
  224. """Return the current file position."""
  225. with self._lock:
  226. self._check_not_closed()
  227. if self._mode == _MODE_READ:
  228. return self._buffer.tell()
  229. return self._pos
  230. def open(filename, mode="rb", compresslevel=9,
  231. encoding=None, errors=None, newline=None):
  232. """Open a bzip2-compressed file in binary or text mode.
  233. The filename argument can be an actual filename (a str, bytes, or
  234. PathLike object), or an existing file object to read from or write
  235. to.
  236. The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or
  237. "ab" for binary mode, or "rt", "wt", "xt" or "at" for text mode.
  238. The default mode is "rb", and the default compresslevel is 9.
  239. For binary mode, this function is equivalent to the BZ2File
  240. constructor: BZ2File(filename, mode, compresslevel). In this case,
  241. the encoding, errors and newline arguments must not be provided.
  242. For text mode, a BZ2File object is created, and wrapped in an
  243. io.TextIOWrapper instance with the specified encoding, error
  244. handling behavior, and line ending(s).
  245. """
  246. if "t" in mode:
  247. if "b" in mode:
  248. raise ValueError("Invalid mode: %r" % (mode,))
  249. else:
  250. if encoding is not None:
  251. raise ValueError("Argument 'encoding' not supported in binary mode")
  252. if errors is not None:
  253. raise ValueError("Argument 'errors' not supported in binary mode")
  254. if newline is not None:
  255. raise ValueError("Argument 'newline' not supported in binary mode")
  256. bz_mode = mode.replace("t", "")
  257. binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel)
  258. if "t" in mode:
  259. return io.TextIOWrapper(binary_file, encoding, errors, newline)
  260. else:
  261. return binary_file
  262. def compress(data, compresslevel=9):
  263. """Compress a block of data.
  264. compresslevel, if given, must be a number between 1 and 9.
  265. For incremental compression, use a BZ2Compressor object instead.
  266. """
  267. comp = BZ2Compressor(compresslevel)
  268. return comp.compress(data) + comp.flush()
  269. def decompress(data):
  270. """Decompress a block of data.
  271. For incremental decompression, use a BZ2Decompressor object instead.
  272. """
  273. results = []
  274. while data:
  275. decomp = BZ2Decompressor()
  276. try:
  277. res = decomp.decompress(data)
  278. except OSError:
  279. if results:
  280. break # Leftover data is not a valid bzip2 stream; ignore it.
  281. else:
  282. raise # Error on the first iteration; bail out.
  283. results.append(res)
  284. if not decomp.eof:
  285. raise ValueError("Compressed data ended before the "
  286. "end-of-stream marker was reached")
  287. data = decomp.unused_data
  288. return b"".join(results)