A read-only wrapper of part of a file.
| 2023 | |
| 2024 | |
| 2025 | class _PartialFile(_ProxyFile): |
| 2026 | """A read-only wrapper of part of a file.""" |
| 2027 | |
| 2028 | def __init__(self, f, start=None, stop=None): |
| 2029 | """Initialize a _PartialFile.""" |
| 2030 | _ProxyFile.__init__(self, f, start) |
| 2031 | self._start = start |
| 2032 | self._stop = stop |
| 2033 | |
| 2034 | def tell(self): |
| 2035 | """Return the position with respect to start.""" |
| 2036 | return _ProxyFile.tell(self) - self._start |
| 2037 | |
| 2038 | def seek(self, offset, whence=0): |
| 2039 | """Change position, possibly with respect to start or stop.""" |
| 2040 | if whence == 0: |
| 2041 | self._pos = self._start |
| 2042 | whence = 1 |
| 2043 | elif whence == 2: |
| 2044 | self._pos = self._stop |
| 2045 | whence = 1 |
| 2046 | _ProxyFile.seek(self, offset, whence) |
| 2047 | |
| 2048 | def _read(self, size, read_method): |
| 2049 | """Read size bytes using read_method, honoring start and stop.""" |
| 2050 | remaining = self._stop - self._pos |
| 2051 | if remaining <= 0: |
| 2052 | return b'' |
| 2053 | if size is None or size < 0 or size > remaining: |
| 2054 | size = remaining |
| 2055 | return _ProxyFile._read(self, size, read_method) |
| 2056 | |
| 2057 | def close(self): |
| 2058 | # do *not* close the underlying file object for partial files, |
| 2059 | # since it's global to the mailbox object |
| 2060 | if hasattr(self, '_file'): |
| 2061 | del self._file |
| 2062 | |
| 2063 | |
| 2064 | def _lock_file(f, dotlock=True): |