You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

499 lines
18 KiB

4 years ago
  1. """Module for reading and writing bzip2-compressed files.
  2. This module contains a backport of Python 3.4's bz2.open() function and
  3. BZ2File class, adapted to work with earlier versions of Python.
  4. """
  5. __all__ = ["BZ2File", "open"]
  6. __author__ = "Nadeem Vawda <nadeem.vawda@gmail.com>"
  7. import io
  8. import sys
  9. import warnings
  10. try:
  11. from threading import RLock
  12. except ImportError:
  13. from dummy_threading import RLock
  14. from bz2 import BZ2Compressor, BZ2Decompressor
  15. _MODE_CLOSED = 0
  16. _MODE_READ = 1
  17. _MODE_READ_EOF = 2
  18. _MODE_WRITE = 3
  19. _BUFFER_SIZE = 8192
  20. _STR_TYPES = (str, unicode) if (str is bytes) else (str, bytes)
  21. # The 'x' mode for open() was introduced in Python 3.3.
  22. _HAS_OPEN_X_MODE = sys.version_info[:2] >= (3, 3)
  23. _builtin_open = open
  24. class BZ2File(io.BufferedIOBase):
  25. """A file object providing transparent bzip2 (de)compression.
  26. A BZ2File can act as a wrapper for an existing file object, or refer
  27. directly to a named file on disk.
  28. Note that BZ2File provides a *binary* file interface - data read is
  29. returned as bytes, and data to be written should be given as bytes.
  30. """
  31. def __init__(self, filename, mode="r", buffering=None, compresslevel=9):
  32. """Open a bzip2-compressed file.
  33. If filename is a str, bytes or unicode object, it gives the name
  34. of the file to be opened. Otherwise, it should be a file object,
  35. which will be used to read or write the compressed data.
  36. mode can be 'r' for reading (default), 'w' for (over)writing,
  37. 'x' for creating exclusively, or 'a' for appending. These can
  38. equivalently be given as 'rb', 'wb', 'xb', and 'ab'.
  39. buffering is ignored. Its use is deprecated.
  40. If mode is 'w', 'x' or 'a', compresslevel can be a number between 1
  41. and 9 specifying the level of compression: 1 produces the least
  42. compression, and 9 (default) produces the most compression.
  43. If mode is 'r', the input file may be the concatenation of
  44. multiple compressed streams.
  45. """
  46. # This lock must be recursive, so that BufferedIOBase's
  47. # readline(), readlines() and writelines() don't deadlock.
  48. self._lock = RLock()
  49. self._fp = None
  50. self._closefp = False
  51. self._mode = _MODE_CLOSED
  52. self._pos = 0
  53. self._size = -1
  54. if buffering is not None:
  55. warnings.warn("Use of 'buffering' argument is deprecated",
  56. DeprecationWarning)
  57. if not (1 <= compresslevel <= 9):
  58. raise ValueError("compresslevel must be between 1 and 9")
  59. if mode in ("", "r", "rb"):
  60. mode = "rb"
  61. mode_code = _MODE_READ
  62. self._decompressor = BZ2Decompressor()
  63. self._buffer = b""
  64. self._buffer_offset = 0
  65. elif mode in ("w", "wb"):
  66. mode = "wb"
  67. mode_code = _MODE_WRITE
  68. self._compressor = BZ2Compressor(compresslevel)
  69. elif mode in ("x", "xb") and _HAS_OPEN_X_MODE:
  70. mode = "xb"
  71. mode_code = _MODE_WRITE
  72. self._compressor = BZ2Compressor(compresslevel)
  73. elif mode in ("a", "ab"):
  74. mode = "ab"
  75. mode_code = _MODE_WRITE
  76. self._compressor = BZ2Compressor(compresslevel)
  77. else:
  78. raise ValueError("Invalid mode: %r" % (mode,))
  79. if isinstance(filename, _STR_TYPES):
  80. self._fp = _builtin_open(filename, mode)
  81. self._closefp = True
  82. self._mode = mode_code
  83. elif hasattr(filename, "read") or hasattr(filename, "write"):
  84. self._fp = filename
  85. self._mode = mode_code
  86. else:
  87. raise TypeError("filename must be a %s or %s object, or a file" %
  88. (_STR_TYPES[0].__name__, _STR_TYPES[1].__name__))
  89. def close(self):
  90. """Flush and close the file.
  91. May be called more than once without error. Once the file is
  92. closed, any other operation on it will raise a ValueError.
  93. """
  94. with self._lock:
  95. if self._mode == _MODE_CLOSED:
  96. return
  97. try:
  98. if self._mode in (_MODE_READ, _MODE_READ_EOF):
  99. self._decompressor = None
  100. elif self._mode == _MODE_WRITE:
  101. self._fp.write(self._compressor.flush())
  102. self._compressor = None
  103. finally:
  104. try:
  105. if self._closefp:
  106. self._fp.close()
  107. finally:
  108. self._fp = None
  109. self._closefp = False
  110. self._mode = _MODE_CLOSED
  111. self._buffer = b""
  112. self._buffer_offset = 0
  113. @property
  114. def closed(self):
  115. """True if this file is closed."""
  116. return self._mode == _MODE_CLOSED
  117. def fileno(self):
  118. """Return the file descriptor for the underlying file."""
  119. self._check_not_closed()
  120. return self._fp.fileno()
  121. def seekable(self):
  122. """Return whether the file supports seeking."""
  123. return self.readable() and (self._fp.seekable()
  124. if hasattr(self._fp, "seekable")
  125. else hasattr(self._fp, "seek"))
  126. def readable(self):
  127. """Return whether the file was opened for reading."""
  128. self._check_not_closed()
  129. return self._mode in (_MODE_READ, _MODE_READ_EOF)
  130. def writable(self):
  131. """Return whether the file was opened for writing."""
  132. self._check_not_closed()
  133. return self._mode == _MODE_WRITE
  134. # Mode-checking helper functions.
  135. def _check_not_closed(self):
  136. if self.closed:
  137. raise ValueError("I/O operation on closed file")
  138. def _check_can_read(self):
  139. if self._mode not in (_MODE_READ, _MODE_READ_EOF):
  140. self._check_not_closed()
  141. raise io.UnsupportedOperation("File not open for reading")
  142. def _check_can_write(self):
  143. if self._mode != _MODE_WRITE:
  144. self._check_not_closed()
  145. raise io.UnsupportedOperation("File not open for writing")
  146. def _check_can_seek(self):
  147. if self._mode not in (_MODE_READ, _MODE_READ_EOF):
  148. self._check_not_closed()
  149. raise io.UnsupportedOperation("Seeking is only supported "
  150. "on files open for reading")
  151. if hasattr(self._fp, "seekable") and not self._fp.seekable():
  152. raise io.UnsupportedOperation("The underlying file object "
  153. "does not support seeking")
  154. # Fill the readahead buffer if it is empty. Returns False on EOF.
  155. def _fill_buffer(self):
  156. if self._mode == _MODE_READ_EOF:
  157. return False
  158. # Depending on the input data, our call to the decompressor may not
  159. # return any data. In this case, try again after reading another block.
  160. while self._buffer_offset == len(self._buffer):
  161. rawblock = (self._decompressor.unused_data or
  162. self._fp.read(_BUFFER_SIZE))
  163. if not rawblock:
  164. try:
  165. self._decompressor.decompress(b"")
  166. except EOFError:
  167. # End-of-stream marker and end of file. We're good.
  168. self._mode = _MODE_READ_EOF
  169. self._size = self._pos
  170. return False
  171. else:
  172. # Problem - we were expecting more compressed data.
  173. raise EOFError("Compressed file ended before the "
  174. "end-of-stream marker was reached")
  175. try:
  176. self._buffer = self._decompressor.decompress(rawblock)
  177. except EOFError:
  178. # Continue to next stream.
  179. self._decompressor = BZ2Decompressor()
  180. try:
  181. self._buffer = self._decompressor.decompress(rawblock)
  182. except IOError:
  183. # Trailing data isn't a valid bzip2 stream. We're done here.
  184. self._mode = _MODE_READ_EOF
  185. self._size = self._pos
  186. return False
  187. self._buffer_offset = 0
  188. return True
  189. # Read data until EOF.
  190. # If return_data is false, consume the data without returning it.
  191. def _read_all(self, return_data=True):
  192. # The loop assumes that _buffer_offset is 0. Ensure that this is true.
  193. self._buffer = self._buffer[self._buffer_offset:]
  194. self._buffer_offset = 0
  195. blocks = []
  196. while self._fill_buffer():
  197. if return_data:
  198. blocks.append(self._buffer)
  199. self._pos += len(self._buffer)
  200. self._buffer = b""
  201. if return_data:
  202. return b"".join(blocks)
  203. # Read a block of up to n bytes.
  204. # If return_data is false, consume the data without returning it.
  205. def _read_block(self, n, return_data=True):
  206. # If we have enough data buffered, return immediately.
  207. end = self._buffer_offset + n
  208. if end <= len(self._buffer):
  209. data = self._buffer[self._buffer_offset : end]
  210. self._buffer_offset = end
  211. self._pos += len(data)
  212. return data if return_data else None
  213. # The loop assumes that _buffer_offset is 0. Ensure that this is true.
  214. self._buffer = self._buffer[self._buffer_offset:]
  215. self._buffer_offset = 0
  216. blocks = []
  217. while n > 0 and self._fill_buffer():
  218. if n < len(self._buffer):
  219. data = self._buffer[:n]
  220. self._buffer_offset = n
  221. else:
  222. data = self._buffer
  223. self._buffer = b""
  224. if return_data:
  225. blocks.append(data)
  226. self._pos += len(data)
  227. n -= len(data)
  228. if return_data:
  229. return b"".join(blocks)
  230. def peek(self, n=0):
  231. """Return buffered data without advancing the file position.
  232. Always returns at least one byte of data, unless at EOF.
  233. The exact number of bytes returned is unspecified.
  234. """
  235. with self._lock:
  236. self._check_can_read()
  237. if not self._fill_buffer():
  238. return b""
  239. return self._buffer[self._buffer_offset:]
  240. def read(self, size=-1):
  241. """Read up to size uncompressed bytes from the file.
  242. If size is negative or omitted, read until EOF is reached.
  243. Returns b'' if the file is already at EOF.
  244. """
  245. if size is None:
  246. raise TypeError()
  247. with self._lock:
  248. self._check_can_read()
  249. if size == 0:
  250. return b""
  251. elif size < 0:
  252. return self._read_all()
  253. else:
  254. return self._read_block(size)
  255. def read1(self, size=-1):
  256. """Read up to size uncompressed bytes, while trying to avoid
  257. making multiple reads from the underlying stream.
  258. Returns b'' if the file is at EOF.
  259. """
  260. # Usually, read1() calls _fp.read() at most once. However, sometimes
  261. # this does not give enough data for the decompressor to make progress.
  262. # In this case we make multiple reads, to avoid returning b"".
  263. with self._lock:
  264. self._check_can_read()
  265. if (size == 0 or
  266. # Only call _fill_buffer() if the buffer is actually empty.
  267. # This gives a significant speedup if *size* is small.
  268. (self._buffer_offset == len(self._buffer) and not self._fill_buffer())):
  269. return b""
  270. if size > 0:
  271. data = self._buffer[self._buffer_offset :
  272. self._buffer_offset + size]
  273. self._buffer_offset += len(data)
  274. else:
  275. data = self._buffer[self._buffer_offset:]
  276. self._buffer = b""
  277. self._buffer_offset = 0
  278. self._pos += len(data)
  279. return data
  280. def readinto(self, b):
  281. """Read up to len(b) bytes into b.
  282. Returns the number of bytes read (0 for EOF).
  283. """
  284. with self._lock:
  285. return io.BufferedIOBase.readinto(self, b)
  286. def readline(self, size=-1):
  287. """Read a line of uncompressed bytes from the file.
  288. The terminating newline (if present) is retained. If size is
  289. non-negative, no more than size bytes will be read (in which
  290. case the line may be incomplete). Returns b'' if already at EOF.
  291. """
  292. if not isinstance(size, int):
  293. if not hasattr(size, "__index__"):
  294. raise TypeError("Integer argument expected")
  295. size = size.__index__()
  296. with self._lock:
  297. self._check_can_read()
  298. # Shortcut for the common case - the whole line is in the buffer.
  299. if size < 0:
  300. end = self._buffer.find(b"\n", self._buffer_offset) + 1
  301. if end > 0:
  302. line = self._buffer[self._buffer_offset : end]
  303. self._buffer_offset = end
  304. self._pos += len(line)
  305. return line
  306. return io.BufferedIOBase.readline(self, size)
  307. def readlines(self, size=-1):
  308. """Read a list of lines of uncompressed bytes from the file.
  309. size can be specified to control the number of lines read: no
  310. further lines will be read once the total size of the lines read
  311. so far equals or exceeds size.
  312. """
  313. if not isinstance(size, int):
  314. if not hasattr(size, "__index__"):
  315. raise TypeError("Integer argument expected")
  316. size = size.__index__()
  317. with self._lock:
  318. return io.BufferedIOBase.readlines(self, size)
  319. def write(self, data):
  320. """Write a byte string to the file.
  321. Returns the number of uncompressed bytes written, which is
  322. always len(data). Note that due to buffering, the file on disk
  323. may not reflect the data written until close() is called.
  324. """
  325. with self._lock:
  326. self._check_can_write()
  327. compressed = self._compressor.compress(data)
  328. self._fp.write(compressed)
  329. self._pos += len(data)
  330. return len(data)
  331. def writelines(self, seq):
  332. """Write a sequence of byte strings to the file.
  333. Returns the number of uncompressed bytes written.
  334. seq can be any iterable yielding byte strings.
  335. Line separators are not added between the written byte strings.
  336. """
  337. with self._lock:
  338. return io.BufferedIOBase.writelines(self, seq)
  339. # Rewind the file to the beginning of the data stream.
  340. def _rewind(self):
  341. self._fp.seek(0, 0)
  342. self._mode = _MODE_READ
  343. self._pos = 0
  344. self._decompressor = BZ2Decompressor()
  345. self._buffer = b""
  346. self._buffer_offset = 0
  347. def seek(self, offset, whence=0):
  348. """Change the file position.
  349. The new position is specified by offset, relative to the
  350. position indicated by whence. Values for whence are:
  351. 0: start of stream (default); offset must not be negative
  352. 1: current stream position
  353. 2: end of stream; offset must not be positive
  354. Returns the new file position.
  355. Note that seeking is emulated, so depending on the parameters,
  356. this operation may be extremely slow.
  357. """
  358. with self._lock:
  359. self._check_can_seek()
  360. # Recalculate offset as an absolute file position.
  361. if whence == 0:
  362. pass
  363. elif whence == 1:
  364. offset = self._pos + offset
  365. elif whence == 2:
  366. # Seeking relative to EOF - we need to know the file's size.
  367. if self._size < 0:
  368. self._read_all(return_data=False)
  369. offset = self._size + offset
  370. else:
  371. raise ValueError("Invalid value for whence: %s" % (whence,))
  372. # Make it so that offset is the number of bytes to skip forward.
  373. if offset < self._pos:
  374. self._rewind()
  375. else:
  376. offset -= self._pos
  377. # Read and discard data until we reach the desired position.
  378. self._read_block(offset, return_data=False)
  379. return self._pos
  380. def tell(self):
  381. """Return the current file position."""
  382. with self._lock:
  383. self._check_not_closed()
  384. return self._pos
  385. def open(filename, mode="rb", compresslevel=9,
  386. encoding=None, errors=None, newline=None):
  387. """Open a bzip2-compressed file in binary or text mode.
  388. The filename argument can be an actual filename (a str, bytes or unicode
  389. object), or an existing file object to read from or write to.
  390. The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or
  391. "ab" for binary mode, or "rt", "wt", "xt" or "at" for text mode.
  392. The default mode is "rb", and the default compresslevel is 9.
  393. For binary mode, this function is equivalent to the BZ2File
  394. constructor: BZ2File(filename, mode, compresslevel). In this case,
  395. the encoding, errors and newline arguments must not be provided.
  396. For text mode, a BZ2File object is created, and wrapped in an
  397. io.TextIOWrapper instance with the specified encoding, error
  398. handling behavior, and line ending(s).
  399. """
  400. if "t" in mode:
  401. if "b" in mode:
  402. raise ValueError("Invalid mode: %r" % (mode,))
  403. else:
  404. if encoding is not None:
  405. raise ValueError("Argument 'encoding' not supported in binary mode")
  406. if errors is not None:
  407. raise ValueError("Argument 'errors' not supported in binary mode")
  408. if newline is not None:
  409. raise ValueError("Argument 'newline' not supported in binary mode")
  410. bz_mode = mode.replace("t", "")
  411. binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel)
  412. if "t" in mode:
  413. return io.TextIOWrapper(binary_file, encoding, errors, newline)
  414. else:
  415. return binary_file