Debian Codegraph @

mrcfile/bzip2mrcfile.py

raw
1 # Copyright (c) 2016, Science and Technology Facilities Council
2 # This software is distributed under a BSD licence. See LICENSE.txt.
3 """
4 bzip2mrcfile
5 ------------
6
7 Module which exports the :class:`Bzip2MrcFile` class.
8
9 Classes:
10 :class:`Bzip2MrcFile`: An object which represents a bzip2-compressed MRC
11 file.
12
13 """
14
15 # Import Python 3 features for future-proofing
16 from __future__ import (absolute_import, division, print_function,
17 unicode_literals)
18
19
20 import bz2
21 import os
22
23 from .mrcfile import MrcFile
24
25
26 class Bzip2MrcFile(MrcFile):
27
28 """:class:`~mrcfile.mrcfile.MrcFile` subclass for handling bzip2-compressed
29 files.
30
31 Usage is the same as for :class:`~mrcfile.mrcfile.MrcFile`.
32
33 """
34
35 def __repr__(self):
36 return "Bzip2MrcFile('{0}', mode='{1}')".format(self._fname,
37 self._mode)
38
39 def _open_file(self, name):
40 """Override _open_file() to open a bzip2 file."""
41 self._fname = name
42 if 'w' in self._mode and not os.path.exists(name):
43 open(name, mode='w').close()
44 self._iostream = bz2.BZ2File(name, mode='r')
45
46 def _read(self, header_only=False):
47 """Override _read() to ensure bzip2 file is in read mode."""
48 self._ensure_readable_bzip2_stream()
49 super(Bzip2MrcFile, self)._read(header_only)
50
51 def _ensure_readable_bzip2_stream(self):
52 """Make sure _iostream is a bzip2 stream that can be read."""
53 if hasattr(self._iostream, "readable"):
54 # Python 3
55 readable = self._iostream.readable()
56 else:
57 # Python 2
58 readable = (self._iostream.mode[0] == 'r')
59 if not readable:
60 self._iostream.close()
61 self._iostream = bz2.BZ2File(self._fname, mode='r')
62
63 def _get_file_size(self):
64 """Override _get_file_size() to ensure stream is readable first."""
65 self._ensure_readable_bzip2_stream()
66 return super(Bzip2MrcFile, self)._get_file_size()
67
68 def _read_bytearray_from_stream(self, number_of_bytes):
69 """Override because BZ2File in Python 2 does not support
70 :meth:`~io.BufferedIOBase.readinto`."""
71 if hasattr(self._iostream, "readinto"):
72 # Python 3 - BZ2File supports ``readinto()`` so we just use the normal implementation
73 return super(Bzip2MrcFile, self)._read_bytearray_from_stream(number_of_bytes)
74 else:
75 # Python 2 - need to read as bytes then copy to a bytearray
76 result_bytes = self._iostream.read(number_of_bytes)
77 return bytearray(result_bytes), len(result_bytes)
78
79 def flush(self):
80 """Override :meth:`~mrcfile.mrcinterpreter.MrcInterpreter.flush` since
81 BZ2File objects need special handling.
82 """
83 if not self._read_only:
84 self._iostream.close()
85 self._iostream = bz2.BZ2File(self._fname, mode='w')
86
87 # Arrays converted to bytes so bz2 can calculate sizes correctly
88 self._iostream.write(self.header.tobytes())
89 self._iostream.write(self.extended_header.tobytes())
90 self._iostream.write(self.data.tobytes())
91 # no equivalent for flush() with BZ2File