bz2.py 12 KB

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