Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1 | """ |
| 2 | Python implementation of the io module. |
| 3 | """ |
| 4 | |
| 5 | import os |
| 6 | import abc |
| 7 | import codecs |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 8 | import errno |
Serhiy Storchaka | 71fd224 | 2015-04-10 16:16:16 +0300 | [diff] [blame] | 9 | import stat |
Serhiy Storchaka | f0f55a0 | 2015-08-28 22:17:04 +0300 | [diff] [blame] | 10 | import sys |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 11 | # Import _thread instead of threading to reduce startup cost |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 12 | from _thread import allocate_lock as Lock |
Serhiy Storchaka | f0f55a0 | 2015-08-28 22:17:04 +0300 | [diff] [blame] | 13 | if sys.platform in {'win32', 'cygwin'}: |
Serhiy Storchaka | 71fd224 | 2015-04-10 16:16:16 +0300 | [diff] [blame] | 14 | from msvcrt import setmode as _setmode |
| 15 | else: |
| 16 | _setmode = None |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 17 | |
| 18 | import io |
Benjamin Peterson | c3be11a | 2010-04-27 21:24:03 +0000 | [diff] [blame] | 19 | from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 20 | |
Jesus Cea | 9436361 | 2012-06-22 18:32:07 +0200 | [diff] [blame] | 21 | valid_seek_flags = {0, 1, 2} # Hardwired values |
| 22 | if hasattr(os, 'SEEK_HOLE') : |
| 23 | valid_seek_flags.add(os.SEEK_HOLE) |
| 24 | valid_seek_flags.add(os.SEEK_DATA) |
| 25 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 26 | # open() uses st_blksize whenever we can |
| 27 | DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes |
| 28 | |
| 29 | # NOTE: Base classes defined here are registered with the "official" ABCs |
Benjamin Peterson | 86fdbf3 | 2015-03-18 21:35:38 -0500 | [diff] [blame] | 30 | # defined in io.py. We don't use real inheritance though, because we don't want |
| 31 | # to inherit the C implementations. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 32 | |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 33 | # Rebind for compatibility |
| 34 | BlockingIOError = BlockingIOError |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 35 | |
| 36 | |
Georg Brandl | 4d73b57 | 2011-01-13 07:13:06 +0000 | [diff] [blame] | 37 | def open(file, mode="r", buffering=-1, encoding=None, errors=None, |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 38 | newline=None, closefd=True, opener=None): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 39 | |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 40 | r"""Open file and return a stream. Raise OSError upon failure. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 41 | |
| 42 | file is either a text or byte string giving the name (and the path |
| 43 | if the file isn't in the current working directory) of the file to |
| 44 | be opened or an integer file descriptor of the file to be |
| 45 | wrapped. (If a file descriptor is given, it is closed when the |
| 46 | returned I/O object is closed, unless closefd is set to False.) |
| 47 | |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 48 | mode is an optional string that specifies the mode in which the file is |
| 49 | opened. It defaults to 'r' which means open for reading in text mode. Other |
| 50 | common values are 'w' for writing (truncating the file if it already |
Charles-François Natali | d612de1 | 2012-01-14 11:51:00 +0100 | [diff] [blame] | 51 | exists), 'x' for exclusive creation of a new file, and 'a' for appending |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 52 | (which on some Unix systems, means that all writes append to the end of the |
| 53 | file regardless of the current seek position). In text mode, if encoding is |
| 54 | not specified the encoding used is platform dependent. (For reading and |
| 55 | writing raw bytes use binary mode and leave encoding unspecified.) The |
| 56 | available modes are: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 57 | |
| 58 | ========= =============================================================== |
| 59 | Character Meaning |
| 60 | --------- --------------------------------------------------------------- |
| 61 | 'r' open for reading (default) |
| 62 | 'w' open for writing, truncating the file first |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 63 | 'x' create a new file and open it for writing |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 64 | 'a' open for writing, appending to the end of the file if it exists |
| 65 | 'b' binary mode |
| 66 | 't' text mode (default) |
| 67 | '+' open a disk file for updating (reading and writing) |
Serhiy Storchaka | 6787a38 | 2013-11-23 22:12:06 +0200 | [diff] [blame] | 68 | 'U' universal newline mode (deprecated) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 69 | ========= =============================================================== |
| 70 | |
| 71 | The default mode is 'rt' (open for reading text). For binary random |
| 72 | access, the mode 'w+b' opens and truncates the file to 0 bytes, while |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 73 | 'r+b' opens the file without truncation. The 'x' mode implies 'w' and |
| 74 | raises an `FileExistsError` if the file already exists. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 75 | |
| 76 | Python distinguishes between files opened in binary and text modes, |
| 77 | even when the underlying operating system doesn't. Files opened in |
| 78 | binary mode (appending 'b' to the mode argument) return contents as |
| 79 | bytes objects without any decoding. In text mode (the default, or when |
| 80 | 't' is appended to the mode argument), the contents of the file are |
| 81 | returned as strings, the bytes having been first decoded using a |
| 82 | platform-dependent encoding or using the specified encoding if given. |
| 83 | |
Serhiy Storchaka | 6787a38 | 2013-11-23 22:12:06 +0200 | [diff] [blame] | 84 | 'U' mode is deprecated and will raise an exception in future versions |
| 85 | of Python. It has no effect in Python 3. Use newline to control |
| 86 | universal newlines mode. |
| 87 | |
Antoine Pitrou | d5587bc | 2009-12-19 21:08:31 +0000 | [diff] [blame] | 88 | buffering is an optional integer used to set the buffering policy. |
| 89 | Pass 0 to switch buffering off (only allowed in binary mode), 1 to select |
| 90 | line buffering (only usable in text mode), and an integer > 1 to indicate |
| 91 | the size of a fixed-size chunk buffer. When no buffering argument is |
| 92 | given, the default buffering policy works as follows: |
| 93 | |
| 94 | * Binary files are buffered in fixed-size chunks; the size of the buffer |
| 95 | is chosen using a heuristic trying to determine the underlying device's |
| 96 | "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`. |
| 97 | On many systems, the buffer will typically be 4096 or 8192 bytes long. |
| 98 | |
| 99 | * "Interactive" text files (files for which isatty() returns True) |
| 100 | use line buffering. Other text files use the policy described above |
| 101 | for binary files. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 102 | |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 103 | encoding is the str name of the encoding used to decode or encode the |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 104 | file. This should only be used in text mode. The default encoding is |
| 105 | platform dependent, but any encoding supported by Python can be |
| 106 | passed. See the codecs module for the list of supported encodings. |
| 107 | |
| 108 | errors is an optional string that specifies how encoding errors are to |
| 109 | be handled---this argument should not be used in binary mode. Pass |
| 110 | 'strict' to raise a ValueError exception if there is an encoding error |
| 111 | (the default of None has the same effect), or pass 'ignore' to ignore |
| 112 | errors. (Note that ignoring encoding errors can lead to data loss.) |
| 113 | See the documentation for codecs.register for a list of the permitted |
| 114 | encoding error strings. |
| 115 | |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 116 | newline is a string controlling how universal newlines works (it only |
| 117 | applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works |
| 118 | as follows: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 119 | |
| 120 | * On input, if newline is None, universal newlines mode is |
| 121 | enabled. Lines in the input can end in '\n', '\r', or '\r\n', and |
| 122 | these are translated into '\n' before being returned to the |
| 123 | caller. If it is '', universal newline mode is enabled, but line |
| 124 | endings are returned to the caller untranslated. If it has any of |
| 125 | the other legal values, input lines are only terminated by the given |
| 126 | string, and the line ending is returned to the caller untranslated. |
| 127 | |
| 128 | * On output, if newline is None, any '\n' characters written are |
| 129 | translated to the system default line separator, os.linesep. If |
| 130 | newline is '', no translation takes place. If newline is any of the |
| 131 | other legal values, any '\n' characters written are translated to |
| 132 | the given string. |
| 133 | |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 134 | closedfd is a bool. If closefd is False, the underlying file descriptor will |
| 135 | be kept open when the file is closed. This does not work when a file name is |
| 136 | given and must be True in that case. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 137 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 138 | The newly created file is non-inheritable. |
| 139 | |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 140 | A custom opener can be used by passing a callable as *opener*. The |
| 141 | underlying file descriptor for the file object is then obtained by calling |
| 142 | *opener* with (*file*, *flags*). *opener* must return an open file |
| 143 | descriptor (passing os.open as *opener* results in functionality similar to |
| 144 | passing None). |
| 145 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 146 | open() returns a file object whose type depends on the mode, and |
| 147 | through which the standard file operations such as reading and writing |
| 148 | are performed. When open() is used to open a file in a text mode ('w', |
| 149 | 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open |
| 150 | a file in a binary mode, the returned class varies: in read binary |
| 151 | mode, it returns a BufferedReader; in write binary and append binary |
| 152 | modes, it returns a BufferedWriter, and in read/write mode, it returns |
| 153 | a BufferedRandom. |
| 154 | |
| 155 | It is also possible to use a string or bytearray as a file for both |
| 156 | reading and writing. For strings StringIO can be used like a file |
| 157 | opened in a text mode, and for bytes a BytesIO can be used like a file |
| 158 | opened in a binary mode. |
| 159 | """ |
Ethan Furman | d62548a | 2016-06-04 14:38:43 -0700 | [diff] [blame] | 160 | if not isinstance(file, int): |
| 161 | file = os.fspath(file) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 162 | if not isinstance(file, (str, bytes, int)): |
| 163 | raise TypeError("invalid file: %r" % file) |
| 164 | if not isinstance(mode, str): |
| 165 | raise TypeError("invalid mode: %r" % mode) |
Benjamin Peterson | 95e392c | 2010-04-27 21:07:21 +0000 | [diff] [blame] | 166 | if not isinstance(buffering, int): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 167 | raise TypeError("invalid buffering: %r" % buffering) |
| 168 | if encoding is not None and not isinstance(encoding, str): |
| 169 | raise TypeError("invalid encoding: %r" % encoding) |
| 170 | if errors is not None and not isinstance(errors, str): |
| 171 | raise TypeError("invalid errors: %r" % errors) |
| 172 | modes = set(mode) |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 173 | if modes - set("axrwb+tU") or len(mode) > len(modes): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 174 | raise ValueError("invalid mode: %r" % mode) |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 175 | creating = "x" in modes |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 176 | reading = "r" in modes |
| 177 | writing = "w" in modes |
| 178 | appending = "a" in modes |
| 179 | updating = "+" in modes |
| 180 | text = "t" in modes |
| 181 | binary = "b" in modes |
| 182 | if "U" in modes: |
Robert Collins | c94a1dc | 2015-07-26 06:43:13 +1200 | [diff] [blame] | 183 | if creating or writing or appending or updating: |
| 184 | raise ValueError("mode U cannot be combined with 'x', 'w', 'a', or '+'") |
Serhiy Storchaka | 6787a38 | 2013-11-23 22:12:06 +0200 | [diff] [blame] | 185 | import warnings |
| 186 | warnings.warn("'U' mode is deprecated", |
| 187 | DeprecationWarning, 2) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 188 | reading = True |
| 189 | if text and binary: |
| 190 | raise ValueError("can't have text and binary mode at once") |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 191 | if creating + reading + writing + appending > 1: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 192 | raise ValueError("can't have read/write/append mode at once") |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 193 | if not (creating or reading or writing or appending): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 194 | raise ValueError("must have exactly one of read/write/append mode") |
| 195 | if binary and encoding is not None: |
| 196 | raise ValueError("binary mode doesn't take an encoding argument") |
| 197 | if binary and errors is not None: |
| 198 | raise ValueError("binary mode doesn't take an errors argument") |
| 199 | if binary and newline is not None: |
| 200 | raise ValueError("binary mode doesn't take a newline argument") |
Alexey Izbyshev | a267056 | 2018-10-20 03:22:31 +0300 | [diff] [blame] | 201 | if binary and buffering == 1: |
| 202 | import warnings |
| 203 | warnings.warn("line buffering (buffering=1) isn't supported in binary " |
| 204 | "mode, the default buffer size will be used", |
| 205 | RuntimeWarning, 2) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 206 | raw = FileIO(file, |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 207 | (creating and "x" or "") + |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 208 | (reading and "r" or "") + |
| 209 | (writing and "w" or "") + |
| 210 | (appending and "a" or "") + |
| 211 | (updating and "+" or ""), |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 212 | closefd, opener=opener) |
Serhiy Storchaka | f10063e | 2014-06-09 13:32:34 +0300 | [diff] [blame] | 213 | result = raw |
| 214 | try: |
| 215 | line_buffering = False |
| 216 | if buffering == 1 or buffering < 0 and raw.isatty(): |
| 217 | buffering = -1 |
| 218 | line_buffering = True |
| 219 | if buffering < 0: |
| 220 | buffering = DEFAULT_BUFFER_SIZE |
| 221 | try: |
| 222 | bs = os.fstat(raw.fileno()).st_blksize |
| 223 | except (OSError, AttributeError): |
| 224 | pass |
| 225 | else: |
| 226 | if bs > 1: |
| 227 | buffering = bs |
| 228 | if buffering < 0: |
| 229 | raise ValueError("invalid buffering size") |
| 230 | if buffering == 0: |
| 231 | if binary: |
| 232 | return result |
| 233 | raise ValueError("can't have unbuffered text I/O") |
| 234 | if updating: |
| 235 | buffer = BufferedRandom(raw, buffering) |
| 236 | elif creating or writing or appending: |
| 237 | buffer = BufferedWriter(raw, buffering) |
| 238 | elif reading: |
| 239 | buffer = BufferedReader(raw, buffering) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 240 | else: |
Serhiy Storchaka | f10063e | 2014-06-09 13:32:34 +0300 | [diff] [blame] | 241 | raise ValueError("unknown mode: %r" % mode) |
| 242 | result = buffer |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 243 | if binary: |
Serhiy Storchaka | f10063e | 2014-06-09 13:32:34 +0300 | [diff] [blame] | 244 | return result |
| 245 | text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering) |
| 246 | result = text |
| 247 | text.mode = mode |
| 248 | return result |
| 249 | except: |
| 250 | result.close() |
| 251 | raise |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 252 | |
| 253 | |
| 254 | class DocDescriptor: |
| 255 | """Helper for builtins.open.__doc__ |
| 256 | """ |
| 257 | def __get__(self, obj, typ): |
| 258 | return ( |
Benjamin Peterson | c3be11a | 2010-04-27 21:24:03 +0000 | [diff] [blame] | 259 | "open(file, mode='r', buffering=-1, encoding=None, " |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 260 | "errors=None, newline=None, closefd=True)\n\n" + |
| 261 | open.__doc__) |
| 262 | |
| 263 | class OpenWrapper: |
| 264 | """Wrapper for builtins.open |
| 265 | |
| 266 | Trick so that open won't become a bound method when stored |
| 267 | as a class variable (as dbm.dumb does). |
| 268 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 269 | See initstdio() in Python/pylifecycle.c. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 270 | """ |
| 271 | __doc__ = DocDescriptor() |
| 272 | |
| 273 | def __new__(cls, *args, **kwargs): |
| 274 | return open(*args, **kwargs) |
| 275 | |
| 276 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 277 | # In normal operation, both `UnsupportedOperation`s should be bound to the |
| 278 | # same object. |
| 279 | try: |
| 280 | UnsupportedOperation = io.UnsupportedOperation |
| 281 | except AttributeError: |
Serhiy Storchaka | 606ab86 | 2016-12-07 13:31:20 +0200 | [diff] [blame] | 282 | class UnsupportedOperation(OSError, ValueError): |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 283 | pass |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 284 | |
| 285 | |
| 286 | class IOBase(metaclass=abc.ABCMeta): |
| 287 | |
| 288 | """The abstract base class for all I/O classes, acting on streams of |
| 289 | bytes. There is no public constructor. |
| 290 | |
| 291 | This class provides dummy implementations for many methods that |
| 292 | derived classes can override selectively; the default implementations |
| 293 | represent a file that cannot be read, written or seeked. |
| 294 | |
Steve Palmer | 7b97ab3 | 2019-04-09 05:35:27 +0100 | [diff] [blame] | 295 | Even though IOBase does not declare read or write because |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 296 | their signatures will vary, implementations and clients should |
| 297 | consider those methods part of the interface. Also, implementations |
Amaury Forgeot d'Arc | 616453c | 2010-09-06 22:31:52 +0000 | [diff] [blame] | 298 | may raise UnsupportedOperation when operations they do not support are |
| 299 | called. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 300 | |
| 301 | The basic type used for binary data read from or written to a file is |
Steve Palmer | 7b97ab3 | 2019-04-09 05:35:27 +0100 | [diff] [blame] | 302 | bytes. Other bytes-like objects are accepted as method arguments too. |
| 303 | Text I/O classes work with str data. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 304 | |
| 305 | Note that calling any method (even inquiries) on a closed stream is |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 306 | undefined. Implementations may raise OSError in this case. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 307 | |
| 308 | IOBase (and its subclasses) support the iterator protocol, meaning |
| 309 | that an IOBase object can be iterated over yielding the lines in a |
| 310 | stream. |
| 311 | |
| 312 | IOBase also supports the :keyword:`with` statement. In this example, |
| 313 | fp is closed after the suite of the with statement is complete: |
| 314 | |
| 315 | with open('spam.txt', 'r') as fp: |
| 316 | fp.write('Spam and eggs!') |
| 317 | """ |
| 318 | |
| 319 | ### Internal ### |
| 320 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 321 | def _unsupported(self, name): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 322 | """Internal: raise an OSError exception for unsupported operations.""" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 323 | raise UnsupportedOperation("%s.%s() not supported" % |
| 324 | (self.__class__.__name__, name)) |
| 325 | |
| 326 | ### Positioning ### |
| 327 | |
Georg Brandl | 4d73b57 | 2011-01-13 07:13:06 +0000 | [diff] [blame] | 328 | def seek(self, pos, whence=0): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 329 | """Change stream position. |
| 330 | |
Terry Jan Reedy | c30b7b1 | 2013-03-11 17:57:08 -0400 | [diff] [blame] | 331 | Change the stream position to byte offset pos. Argument pos is |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 332 | interpreted relative to the position indicated by whence. Values |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 333 | for whence are ints: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 334 | |
| 335 | * 0 -- start of stream (the default); offset should be zero or positive |
| 336 | * 1 -- current stream position; offset may be negative |
| 337 | * 2 -- end of stream; offset is usually negative |
Jesus Cea | 9436361 | 2012-06-22 18:32:07 +0200 | [diff] [blame] | 338 | Some operating systems / file systems could provide additional values. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 339 | |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 340 | Return an int indicating the new absolute position. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 341 | """ |
| 342 | self._unsupported("seek") |
| 343 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 344 | def tell(self): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 345 | """Return an int indicating the current stream position.""" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 346 | return self.seek(0, 1) |
| 347 | |
Georg Brandl | 4d73b57 | 2011-01-13 07:13:06 +0000 | [diff] [blame] | 348 | def truncate(self, pos=None): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 349 | """Truncate file to size bytes. |
| 350 | |
| 351 | Size defaults to the current IO position as reported by tell(). Return |
| 352 | the new size. |
| 353 | """ |
| 354 | self._unsupported("truncate") |
| 355 | |
| 356 | ### Flush and close ### |
| 357 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 358 | def flush(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 359 | """Flush write buffers, if applicable. |
| 360 | |
| 361 | This is not implemented for read-only and non-blocking streams. |
| 362 | """ |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 363 | self._checkClosed() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 364 | # XXX Should this return the number of bytes written??? |
| 365 | |
| 366 | __closed = False |
| 367 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 368 | def close(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 369 | """Flush and close the IO object. |
| 370 | |
| 371 | This method has no effect if the file is already closed. |
| 372 | """ |
| 373 | if not self.__closed: |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 374 | try: |
| 375 | self.flush() |
| 376 | finally: |
| 377 | self.__closed = True |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 378 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 379 | def __del__(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 380 | """Destructor. Calls close().""" |
| 381 | # The try/except block is in case this is called at program |
| 382 | # exit time, when it's possible that globals have already been |
| 383 | # deleted, and then the close() call might fail. Since |
| 384 | # there's nothing we can do about such failures and they annoy |
| 385 | # the end users, we suppress the traceback. |
| 386 | try: |
| 387 | self.close() |
| 388 | except: |
| 389 | pass |
| 390 | |
| 391 | ### Inquiries ### |
| 392 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 393 | def seekable(self): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 394 | """Return a bool indicating whether object supports random access. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 395 | |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 396 | If False, seek(), tell() and truncate() will raise OSError. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 397 | This method may need to do a test seek(). |
| 398 | """ |
| 399 | return False |
| 400 | |
| 401 | def _checkSeekable(self, msg=None): |
Amaury Forgeot d'Arc | ada9948 | 2010-09-06 22:23:13 +0000 | [diff] [blame] | 402 | """Internal: raise UnsupportedOperation if file is not seekable |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 403 | """ |
| 404 | if not self.seekable(): |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 405 | raise UnsupportedOperation("File or stream is not seekable." |
| 406 | if msg is None else msg) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 407 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 408 | def readable(self): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 409 | """Return a bool indicating whether object was opened for reading. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 410 | |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 411 | If False, read() will raise OSError. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 412 | """ |
| 413 | return False |
| 414 | |
| 415 | def _checkReadable(self, msg=None): |
Amaury Forgeot d'Arc | ada9948 | 2010-09-06 22:23:13 +0000 | [diff] [blame] | 416 | """Internal: raise UnsupportedOperation if file is not readable |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 417 | """ |
| 418 | if not self.readable(): |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 419 | raise UnsupportedOperation("File or stream is not readable." |
| 420 | if msg is None else msg) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 421 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 422 | def writable(self): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 423 | """Return a bool indicating whether object was opened for writing. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 424 | |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 425 | If False, write() and truncate() will raise OSError. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 426 | """ |
| 427 | return False |
| 428 | |
| 429 | def _checkWritable(self, msg=None): |
Amaury Forgeot d'Arc | ada9948 | 2010-09-06 22:23:13 +0000 | [diff] [blame] | 430 | """Internal: raise UnsupportedOperation if file is not writable |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 431 | """ |
| 432 | if not self.writable(): |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 433 | raise UnsupportedOperation("File or stream is not writable." |
| 434 | if msg is None else msg) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 435 | |
| 436 | @property |
| 437 | def closed(self): |
| 438 | """closed: bool. True iff the file has been closed. |
| 439 | |
| 440 | For backwards compatibility, this is a property, not a predicate. |
| 441 | """ |
| 442 | return self.__closed |
| 443 | |
| 444 | def _checkClosed(self, msg=None): |
Serhiy Storchaka | 6a7b3a7 | 2016-04-17 08:32:47 +0300 | [diff] [blame] | 445 | """Internal: raise a ValueError if file is closed |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 446 | """ |
| 447 | if self.closed: |
| 448 | raise ValueError("I/O operation on closed file." |
| 449 | if msg is None else msg) |
| 450 | |
| 451 | ### Context manager ### |
| 452 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 453 | def __enter__(self): # That's a forward reference |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 454 | """Context management protocol. Returns self (an instance of IOBase).""" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 455 | self._checkClosed() |
| 456 | return self |
| 457 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 458 | def __exit__(self, *args): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 459 | """Context management protocol. Calls close()""" |
| 460 | self.close() |
| 461 | |
| 462 | ### Lower-level APIs ### |
| 463 | |
| 464 | # XXX Should these be present even if unimplemented? |
| 465 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 466 | def fileno(self): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 467 | """Returns underlying file descriptor (an int) if one exists. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 468 | |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 469 | An OSError is raised if the IO object does not use a file descriptor. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 470 | """ |
| 471 | self._unsupported("fileno") |
| 472 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 473 | def isatty(self): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 474 | """Return a bool indicating whether this is an 'interactive' stream. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 475 | |
| 476 | Return False if it can't be determined. |
| 477 | """ |
| 478 | self._checkClosed() |
| 479 | return False |
| 480 | |
| 481 | ### Readline[s] and writelines ### |
| 482 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 483 | def readline(self, size=-1): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 484 | r"""Read and return a line of bytes from the stream. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 485 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 486 | If size is specified, at most size bytes will be read. |
| 487 | Size should be an int. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 488 | |
| 489 | The line terminator is always b'\n' for binary files; for text |
| 490 | files, the newlines argument to open can be used to select the line |
| 491 | terminator(s) recognized. |
| 492 | """ |
| 493 | # For backwards compatibility, a (slowish) readline(). |
| 494 | if hasattr(self, "peek"): |
| 495 | def nreadahead(): |
| 496 | readahead = self.peek(1) |
| 497 | if not readahead: |
| 498 | return 1 |
| 499 | n = (readahead.find(b"\n") + 1) or len(readahead) |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 500 | if size >= 0: |
| 501 | n = min(n, size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 502 | return n |
| 503 | else: |
| 504 | def nreadahead(): |
| 505 | return 1 |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 506 | if size is None: |
| 507 | size = -1 |
Oren Milman | de50360 | 2017-08-24 21:33:42 +0300 | [diff] [blame] | 508 | else: |
| 509 | try: |
| 510 | size_index = size.__index__ |
| 511 | except AttributeError: |
| 512 | raise TypeError(f"{size!r} is not an integer") |
| 513 | else: |
| 514 | size = size_index() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 515 | res = bytearray() |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 516 | while size < 0 or len(res) < size: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 517 | b = self.read(nreadahead()) |
| 518 | if not b: |
| 519 | break |
| 520 | res += b |
| 521 | if res.endswith(b"\n"): |
| 522 | break |
| 523 | return bytes(res) |
| 524 | |
| 525 | def __iter__(self): |
| 526 | self._checkClosed() |
| 527 | return self |
| 528 | |
| 529 | def __next__(self): |
| 530 | line = self.readline() |
| 531 | if not line: |
| 532 | raise StopIteration |
| 533 | return line |
| 534 | |
| 535 | def readlines(self, hint=None): |
| 536 | """Return a list of lines from the stream. |
| 537 | |
| 538 | hint can be specified to control the number of lines read: no more |
| 539 | lines will be read if the total size (in bytes/characters) of all |
| 540 | lines so far exceeds hint. |
| 541 | """ |
| 542 | if hint is None or hint <= 0: |
| 543 | return list(self) |
| 544 | n = 0 |
| 545 | lines = [] |
| 546 | for line in self: |
| 547 | lines.append(line) |
| 548 | n += len(line) |
| 549 | if n >= hint: |
| 550 | break |
| 551 | return lines |
| 552 | |
| 553 | def writelines(self, lines): |
Marcin Niemira | ab86521 | 2019-04-22 21:13:51 +1000 | [diff] [blame] | 554 | """Write a list of lines to the stream. |
| 555 | |
| 556 | Line separators are not added, so it is usual for each of the lines |
| 557 | provided to have a line separator at the end. |
| 558 | """ |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 559 | self._checkClosed() |
| 560 | for line in lines: |
| 561 | self.write(line) |
| 562 | |
| 563 | io.IOBase.register(IOBase) |
| 564 | |
| 565 | |
| 566 | class RawIOBase(IOBase): |
| 567 | |
| 568 | """Base class for raw binary I/O.""" |
| 569 | |
| 570 | # The read() method is implemented by calling readinto(); derived |
| 571 | # classes that want to support read() only need to implement |
| 572 | # readinto() as a primitive operation. In general, readinto() can be |
| 573 | # more efficient than read(). |
| 574 | |
| 575 | # (It would be tempting to also provide an implementation of |
| 576 | # readinto() in terms of read(), in case the latter is a more suitable |
| 577 | # primitive operation, but that would lead to nasty recursion in case |
| 578 | # a subclass doesn't implement either.) |
| 579 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 580 | def read(self, size=-1): |
| 581 | """Read and return up to size bytes, where size is an int. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 582 | |
| 583 | Returns an empty bytes object on EOF, or None if the object is |
| 584 | set not to block and has no data to read. |
| 585 | """ |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 586 | if size is None: |
| 587 | size = -1 |
| 588 | if size < 0: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 589 | return self.readall() |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 590 | b = bytearray(size.__index__()) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 591 | n = self.readinto(b) |
Antoine Pitrou | 328ec74 | 2010-09-14 18:37:24 +0000 | [diff] [blame] | 592 | if n is None: |
| 593 | return None |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 594 | del b[n:] |
| 595 | return bytes(b) |
| 596 | |
| 597 | def readall(self): |
| 598 | """Read until EOF, using multiple read() call.""" |
| 599 | res = bytearray() |
| 600 | while True: |
| 601 | data = self.read(DEFAULT_BUFFER_SIZE) |
| 602 | if not data: |
| 603 | break |
| 604 | res += data |
Victor Stinner | a80987f | 2011-05-25 22:47:16 +0200 | [diff] [blame] | 605 | if res: |
| 606 | return bytes(res) |
| 607 | else: |
| 608 | # b'' or None |
| 609 | return data |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 610 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 611 | def readinto(self, b): |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 612 | """Read bytes into a pre-allocated bytes-like object b. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 613 | |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 614 | Returns an int representing the number of bytes read (0 for EOF), or |
| 615 | None if the object is set not to block and has no data to read. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 616 | """ |
| 617 | self._unsupported("readinto") |
| 618 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 619 | def write(self, b): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 620 | """Write the given buffer to the IO stream. |
| 621 | |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 622 | Returns the number of bytes written, which may be less than the |
| 623 | length of b in bytes. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 624 | """ |
| 625 | self._unsupported("write") |
| 626 | |
| 627 | io.RawIOBase.register(RawIOBase) |
| 628 | from _io import FileIO |
| 629 | RawIOBase.register(FileIO) |
| 630 | |
| 631 | |
| 632 | class BufferedIOBase(IOBase): |
| 633 | |
| 634 | """Base class for buffered IO objects. |
| 635 | |
| 636 | The main difference with RawIOBase is that the read() method |
| 637 | supports omitting the size argument, and does not have a default |
| 638 | implementation that defers to readinto(). |
| 639 | |
| 640 | In addition, read(), readinto() and write() may raise |
| 641 | BlockingIOError if the underlying raw stream is in non-blocking |
| 642 | mode and not ready; unlike their raw counterparts, they will never |
| 643 | return None. |
| 644 | |
| 645 | A typical implementation should not inherit from a RawIOBase |
| 646 | implementation, but wrap one. |
| 647 | """ |
| 648 | |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 649 | def read(self, size=-1): |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 650 | """Read and return up to size bytes, where size is an int. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 651 | |
| 652 | If the argument is omitted, None, or negative, reads and |
| 653 | returns all data until EOF. |
| 654 | |
| 655 | If the argument is positive, and the underlying raw stream is |
| 656 | not 'interactive', multiple raw reads may be issued to satisfy |
| 657 | the byte count (unless EOF is reached first). But for |
| 658 | interactive raw streams (XXX and for pipes?), at most one raw |
| 659 | read will be issued, and a short result does not imply that |
| 660 | EOF is imminent. |
| 661 | |
| 662 | Returns an empty bytes array on EOF. |
| 663 | |
| 664 | Raises BlockingIOError if the underlying raw stream has no |
| 665 | data at the moment. |
| 666 | """ |
| 667 | self._unsupported("read") |
| 668 | |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 669 | def read1(self, size=-1): |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 670 | """Read up to size bytes with at most one read() system call, |
| 671 | where size is an int. |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 672 | """ |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 673 | self._unsupported("read1") |
| 674 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 675 | def readinto(self, b): |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 676 | """Read bytes into a pre-allocated bytes-like object b. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 677 | |
| 678 | Like read(), this may issue multiple reads to the underlying raw |
| 679 | stream, unless the latter is 'interactive'. |
| 680 | |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 681 | Returns an int representing the number of bytes read (0 for EOF). |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 682 | |
| 683 | Raises BlockingIOError if the underlying raw stream has no |
| 684 | data at the moment. |
| 685 | """ |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 686 | |
| 687 | return self._readinto(b, read1=False) |
| 688 | |
| 689 | def readinto1(self, b): |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 690 | """Read bytes into buffer *b*, using at most one system call |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 691 | |
| 692 | Returns an int representing the number of bytes read (0 for EOF). |
| 693 | |
| 694 | Raises BlockingIOError if the underlying raw stream has no |
| 695 | data at the moment. |
| 696 | """ |
| 697 | |
| 698 | return self._readinto(b, read1=True) |
| 699 | |
| 700 | def _readinto(self, b, read1): |
| 701 | if not isinstance(b, memoryview): |
| 702 | b = memoryview(b) |
| 703 | b = b.cast('B') |
| 704 | |
| 705 | if read1: |
| 706 | data = self.read1(len(b)) |
| 707 | else: |
| 708 | data = self.read(len(b)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 709 | n = len(data) |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 710 | |
| 711 | b[:n] = data |
| 712 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 713 | return n |
| 714 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 715 | def write(self, b): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 716 | """Write the given bytes buffer to the IO stream. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 717 | |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 718 | Return the number of bytes written, which is always the length of b |
| 719 | in bytes. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 720 | |
| 721 | Raises BlockingIOError if the buffer is full and the |
| 722 | underlying raw stream cannot accept more data at the moment. |
| 723 | """ |
| 724 | self._unsupported("write") |
| 725 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 726 | def detach(self): |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 727 | """ |
| 728 | Separate the underlying raw stream from the buffer and return it. |
| 729 | |
| 730 | After the raw stream has been detached, the buffer is in an unusable |
| 731 | state. |
| 732 | """ |
| 733 | self._unsupported("detach") |
| 734 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 735 | io.BufferedIOBase.register(BufferedIOBase) |
| 736 | |
| 737 | |
| 738 | class _BufferedIOMixin(BufferedIOBase): |
| 739 | |
| 740 | """A mixin implementation of BufferedIOBase with an underlying raw stream. |
| 741 | |
| 742 | This passes most requests on to the underlying raw stream. It |
| 743 | does *not* provide implementations of read(), readinto() or |
| 744 | write(). |
| 745 | """ |
| 746 | |
| 747 | def __init__(self, raw): |
Antoine Pitrou | 7f8f418 | 2010-12-21 21:20:59 +0000 | [diff] [blame] | 748 | self._raw = raw |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 749 | |
| 750 | ### Positioning ### |
| 751 | |
| 752 | def seek(self, pos, whence=0): |
| 753 | new_position = self.raw.seek(pos, whence) |
| 754 | if new_position < 0: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 755 | raise OSError("seek() returned an invalid position") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 756 | return new_position |
| 757 | |
| 758 | def tell(self): |
| 759 | pos = self.raw.tell() |
| 760 | if pos < 0: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 761 | raise OSError("tell() returned an invalid position") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 762 | return pos |
| 763 | |
| 764 | def truncate(self, pos=None): |
| 765 | # Flush the stream. We're mixing buffered I/O with lower-level I/O, |
| 766 | # and a flush may be necessary to synch both views of the current |
| 767 | # file state. |
| 768 | self.flush() |
| 769 | |
| 770 | if pos is None: |
| 771 | pos = self.tell() |
| 772 | # XXX: Should seek() be used, instead of passing the position |
| 773 | # XXX directly to truncate? |
| 774 | return self.raw.truncate(pos) |
| 775 | |
| 776 | ### Flush and close ### |
| 777 | |
| 778 | def flush(self): |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 779 | if self.closed: |
Jim Fasarakis-Hilliard | 1e73dbb | 2017-03-26 23:59:08 +0300 | [diff] [blame] | 780 | raise ValueError("flush on closed file") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 781 | self.raw.flush() |
| 782 | |
| 783 | def close(self): |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 784 | if self.raw is not None and not self.closed: |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 785 | try: |
| 786 | # may raise BlockingIOError or BrokenPipeError etc |
| 787 | self.flush() |
| 788 | finally: |
| 789 | self.raw.close() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 790 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 791 | def detach(self): |
| 792 | if self.raw is None: |
| 793 | raise ValueError("raw stream already detached") |
| 794 | self.flush() |
Antoine Pitrou | 7f8f418 | 2010-12-21 21:20:59 +0000 | [diff] [blame] | 795 | raw = self._raw |
| 796 | self._raw = None |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 797 | return raw |
| 798 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 799 | ### Inquiries ### |
| 800 | |
| 801 | def seekable(self): |
| 802 | return self.raw.seekable() |
| 803 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 804 | @property |
Antoine Pitrou | 7f8f418 | 2010-12-21 21:20:59 +0000 | [diff] [blame] | 805 | def raw(self): |
| 806 | return self._raw |
| 807 | |
| 808 | @property |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 809 | def closed(self): |
| 810 | return self.raw.closed |
| 811 | |
| 812 | @property |
| 813 | def name(self): |
| 814 | return self.raw.name |
| 815 | |
| 816 | @property |
| 817 | def mode(self): |
| 818 | return self.raw.mode |
| 819 | |
Antoine Pitrou | 243757e | 2010-11-05 21:15:39 +0000 | [diff] [blame] | 820 | def __getstate__(self): |
Serhiy Storchaka | 0353b4e | 2018-10-31 02:28:07 +0200 | [diff] [blame] | 821 | raise TypeError(f"cannot pickle {self.__class__.__name__!r} object") |
Antoine Pitrou | 243757e | 2010-11-05 21:15:39 +0000 | [diff] [blame] | 822 | |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 823 | def __repr__(self): |
Serhiy Storchaka | 465e60e | 2014-07-25 23:36:00 +0300 | [diff] [blame] | 824 | modname = self.__class__.__module__ |
| 825 | clsname = self.__class__.__qualname__ |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 826 | try: |
| 827 | name = self.name |
Benjamin Peterson | 10e76b6 | 2014-12-21 20:51:50 -0600 | [diff] [blame] | 828 | except Exception: |
Serhiy Storchaka | 465e60e | 2014-07-25 23:36:00 +0300 | [diff] [blame] | 829 | return "<{}.{}>".format(modname, clsname) |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 830 | else: |
Serhiy Storchaka | 465e60e | 2014-07-25 23:36:00 +0300 | [diff] [blame] | 831 | return "<{}.{} name={!r}>".format(modname, clsname, name) |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 832 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 833 | ### Lower-level APIs ### |
| 834 | |
| 835 | def fileno(self): |
| 836 | return self.raw.fileno() |
| 837 | |
| 838 | def isatty(self): |
| 839 | return self.raw.isatty() |
| 840 | |
| 841 | |
| 842 | class BytesIO(BufferedIOBase): |
| 843 | |
| 844 | """Buffered I/O implementation using an in-memory bytes buffer.""" |
| 845 | |
| 846 | def __init__(self, initial_bytes=None): |
| 847 | buf = bytearray() |
| 848 | if initial_bytes is not None: |
| 849 | buf += initial_bytes |
| 850 | self._buffer = buf |
| 851 | self._pos = 0 |
| 852 | |
Alexandre Vassalotti | cf76e1a | 2009-07-22 03:24:36 +0000 | [diff] [blame] | 853 | def __getstate__(self): |
| 854 | if self.closed: |
| 855 | raise ValueError("__getstate__ on closed file") |
| 856 | return self.__dict__.copy() |
| 857 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 858 | def getvalue(self): |
| 859 | """Return the bytes value (contents) of the buffer |
| 860 | """ |
| 861 | if self.closed: |
| 862 | raise ValueError("getvalue on closed file") |
| 863 | return bytes(self._buffer) |
| 864 | |
Antoine Pitrou | 972ee13 | 2010-09-06 18:48:21 +0000 | [diff] [blame] | 865 | def getbuffer(self): |
| 866 | """Return a readable and writable view of the buffer. |
| 867 | """ |
Serhiy Storchaka | c057c38 | 2015-02-03 02:00:18 +0200 | [diff] [blame] | 868 | if self.closed: |
| 869 | raise ValueError("getbuffer on closed file") |
Antoine Pitrou | 972ee13 | 2010-09-06 18:48:21 +0000 | [diff] [blame] | 870 | return memoryview(self._buffer) |
| 871 | |
Serhiy Storchaka | c057c38 | 2015-02-03 02:00:18 +0200 | [diff] [blame] | 872 | def close(self): |
| 873 | self._buffer.clear() |
| 874 | super().close() |
| 875 | |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 876 | def read(self, size=-1): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 877 | if self.closed: |
| 878 | raise ValueError("read from closed file") |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 879 | if size is None: |
| 880 | size = -1 |
Oren Milman | de50360 | 2017-08-24 21:33:42 +0300 | [diff] [blame] | 881 | else: |
| 882 | try: |
| 883 | size_index = size.__index__ |
| 884 | except AttributeError: |
| 885 | raise TypeError(f"{size!r} is not an integer") |
| 886 | else: |
| 887 | size = size_index() |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 888 | if size < 0: |
| 889 | size = len(self._buffer) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 890 | if len(self._buffer) <= self._pos: |
| 891 | return b"" |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 892 | newpos = min(len(self._buffer), self._pos + size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 893 | b = self._buffer[self._pos : newpos] |
| 894 | self._pos = newpos |
| 895 | return bytes(b) |
| 896 | |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 897 | def read1(self, size=-1): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 898 | """This is the same as read. |
| 899 | """ |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 900 | return self.read(size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 901 | |
| 902 | def write(self, b): |
| 903 | if self.closed: |
| 904 | raise ValueError("write to closed file") |
| 905 | if isinstance(b, str): |
| 906 | raise TypeError("can't write str to binary stream") |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 907 | with memoryview(b) as view: |
| 908 | n = view.nbytes # Size of any bytes-like object |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 909 | if n == 0: |
| 910 | return 0 |
| 911 | pos = self._pos |
| 912 | if pos > len(self._buffer): |
| 913 | # Inserts null bytes between the current end of the file |
| 914 | # and the new write position. |
| 915 | padding = b'\x00' * (pos - len(self._buffer)) |
| 916 | self._buffer += padding |
| 917 | self._buffer[pos:pos + n] = b |
| 918 | self._pos += n |
| 919 | return n |
| 920 | |
| 921 | def seek(self, pos, whence=0): |
| 922 | if self.closed: |
| 923 | raise ValueError("seek on closed file") |
| 924 | try: |
Oren Milman | de50360 | 2017-08-24 21:33:42 +0300 | [diff] [blame] | 925 | pos_index = pos.__index__ |
| 926 | except AttributeError: |
| 927 | raise TypeError(f"{pos!r} is not an integer") |
| 928 | else: |
| 929 | pos = pos_index() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 930 | if whence == 0: |
| 931 | if pos < 0: |
| 932 | raise ValueError("negative seek position %r" % (pos,)) |
| 933 | self._pos = pos |
| 934 | elif whence == 1: |
| 935 | self._pos = max(0, self._pos + pos) |
| 936 | elif whence == 2: |
| 937 | self._pos = max(0, len(self._buffer) + pos) |
| 938 | else: |
Jesus Cea | 9436361 | 2012-06-22 18:32:07 +0200 | [diff] [blame] | 939 | raise ValueError("unsupported whence value") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 940 | return self._pos |
| 941 | |
| 942 | def tell(self): |
| 943 | if self.closed: |
| 944 | raise ValueError("tell on closed file") |
| 945 | return self._pos |
| 946 | |
| 947 | def truncate(self, pos=None): |
| 948 | if self.closed: |
| 949 | raise ValueError("truncate on closed file") |
| 950 | if pos is None: |
| 951 | pos = self._pos |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 952 | else: |
| 953 | try: |
Oren Milman | de50360 | 2017-08-24 21:33:42 +0300 | [diff] [blame] | 954 | pos_index = pos.__index__ |
| 955 | except AttributeError: |
| 956 | raise TypeError(f"{pos!r} is not an integer") |
| 957 | else: |
| 958 | pos = pos_index() |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 959 | if pos < 0: |
| 960 | raise ValueError("negative truncate position %r" % (pos,)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 961 | del self._buffer[pos:] |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 962 | return pos |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 963 | |
| 964 | def readable(self): |
Antoine Pitrou | 1d85745 | 2012-09-05 20:11:49 +0200 | [diff] [blame] | 965 | if self.closed: |
| 966 | raise ValueError("I/O operation on closed file.") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 967 | return True |
| 968 | |
| 969 | def writable(self): |
Antoine Pitrou | 1d85745 | 2012-09-05 20:11:49 +0200 | [diff] [blame] | 970 | if self.closed: |
| 971 | raise ValueError("I/O operation on closed file.") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 972 | return True |
| 973 | |
| 974 | def seekable(self): |
Antoine Pitrou | 1d85745 | 2012-09-05 20:11:49 +0200 | [diff] [blame] | 975 | if self.closed: |
| 976 | raise ValueError("I/O operation on closed file.") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 977 | return True |
| 978 | |
| 979 | |
| 980 | class BufferedReader(_BufferedIOMixin): |
| 981 | |
| 982 | """BufferedReader(raw[, buffer_size]) |
| 983 | |
| 984 | A buffer for a readable, sequential BaseRawIO object. |
| 985 | |
| 986 | The constructor creates a BufferedReader for the given readable raw |
| 987 | stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE |
| 988 | is used. |
| 989 | """ |
| 990 | |
| 991 | def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): |
| 992 | """Create a new buffered reader using the given readable raw IO object. |
| 993 | """ |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 994 | if not raw.readable(): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 995 | raise OSError('"raw" argument must be readable.') |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 996 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 997 | _BufferedIOMixin.__init__(self, raw) |
| 998 | if buffer_size <= 0: |
| 999 | raise ValueError("invalid buffer size") |
| 1000 | self.buffer_size = buffer_size |
| 1001 | self._reset_read_buf() |
| 1002 | self._read_lock = Lock() |
| 1003 | |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 1004 | def readable(self): |
| 1005 | return self.raw.readable() |
| 1006 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1007 | def _reset_read_buf(self): |
| 1008 | self._read_buf = b"" |
| 1009 | self._read_pos = 0 |
| 1010 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1011 | def read(self, size=None): |
| 1012 | """Read size bytes. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1013 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1014 | Returns exactly size bytes of data unless the underlying raw IO |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1015 | stream reaches EOF or if the call would block in non-blocking |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1016 | mode. If size is negative, read until EOF or until read() would |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1017 | block. |
| 1018 | """ |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1019 | if size is not None and size < -1: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1020 | raise ValueError("invalid number of bytes to read") |
| 1021 | with self._read_lock: |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1022 | return self._read_unlocked(size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1023 | |
| 1024 | def _read_unlocked(self, n=None): |
| 1025 | nodata_val = b"" |
| 1026 | empty_values = (b"", None) |
| 1027 | buf = self._read_buf |
| 1028 | pos = self._read_pos |
| 1029 | |
| 1030 | # Special case for when the number of bytes to read is unspecified. |
| 1031 | if n is None or n == -1: |
| 1032 | self._reset_read_buf() |
Victor Stinner | b57f108 | 2011-05-26 00:19:38 +0200 | [diff] [blame] | 1033 | if hasattr(self.raw, 'readall'): |
| 1034 | chunk = self.raw.readall() |
| 1035 | if chunk is None: |
| 1036 | return buf[pos:] or None |
| 1037 | else: |
| 1038 | return buf[pos:] + chunk |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1039 | chunks = [buf[pos:]] # Strip the consumed bytes. |
| 1040 | current_size = 0 |
| 1041 | while True: |
| 1042 | # Read until EOF or until read() would block. |
Charles-François Natali | 6e6c59b | 2015-02-07 13:27:50 +0000 | [diff] [blame] | 1043 | chunk = self.raw.read() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1044 | if chunk in empty_values: |
| 1045 | nodata_val = chunk |
| 1046 | break |
| 1047 | current_size += len(chunk) |
| 1048 | chunks.append(chunk) |
| 1049 | return b"".join(chunks) or nodata_val |
| 1050 | |
| 1051 | # The number of bytes to read is specified, return at most n bytes. |
| 1052 | avail = len(buf) - pos # Length of the available buffered data. |
| 1053 | if n <= avail: |
| 1054 | # Fast path: the data to read is fully buffered. |
| 1055 | self._read_pos += n |
| 1056 | return buf[pos:pos+n] |
| 1057 | # Slow path: read from the stream until enough bytes are read, |
| 1058 | # or until an EOF occurs or until read() would block. |
| 1059 | chunks = [buf[pos:]] |
| 1060 | wanted = max(self.buffer_size, n) |
| 1061 | while avail < n: |
Charles-François Natali | 6e6c59b | 2015-02-07 13:27:50 +0000 | [diff] [blame] | 1062 | chunk = self.raw.read(wanted) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1063 | if chunk in empty_values: |
| 1064 | nodata_val = chunk |
| 1065 | break |
| 1066 | avail += len(chunk) |
| 1067 | chunks.append(chunk) |
Martin Panter | e26da7c | 2016-06-02 10:07:09 +0000 | [diff] [blame] | 1068 | # n is more than avail only when an EOF occurred or when |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1069 | # read() would have blocked. |
| 1070 | n = min(n, avail) |
| 1071 | out = b"".join(chunks) |
| 1072 | self._read_buf = out[n:] # Save the extra data in the buffer. |
| 1073 | self._read_pos = 0 |
| 1074 | return out[:n] if out else nodata_val |
| 1075 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1076 | def peek(self, size=0): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1077 | """Returns buffered bytes without advancing the position. |
| 1078 | |
| 1079 | The argument indicates a desired minimal number of bytes; we |
| 1080 | do at most one raw read to satisfy it. We never return more |
| 1081 | than self.buffer_size. |
| 1082 | """ |
| 1083 | with self._read_lock: |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1084 | return self._peek_unlocked(size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1085 | |
| 1086 | def _peek_unlocked(self, n=0): |
| 1087 | want = min(n, self.buffer_size) |
| 1088 | have = len(self._read_buf) - self._read_pos |
| 1089 | if have < want or have <= 0: |
| 1090 | to_read = self.buffer_size - have |
Charles-François Natali | 6e6c59b | 2015-02-07 13:27:50 +0000 | [diff] [blame] | 1091 | current = self.raw.read(to_read) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1092 | if current: |
| 1093 | self._read_buf = self._read_buf[self._read_pos:] + current |
| 1094 | self._read_pos = 0 |
| 1095 | return self._read_buf[self._read_pos:] |
| 1096 | |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 1097 | def read1(self, size=-1): |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1098 | """Reads up to size bytes, with at most one read() system call.""" |
| 1099 | # Returns up to size bytes. If at least one byte is buffered, we |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1100 | # only return buffered bytes. Otherwise, we do one raw read. |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1101 | if size < 0: |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 1102 | size = self.buffer_size |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1103 | if size == 0: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1104 | return b"" |
| 1105 | with self._read_lock: |
| 1106 | self._peek_unlocked(1) |
| 1107 | return self._read_unlocked( |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1108 | min(size, len(self._read_buf) - self._read_pos)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1109 | |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 1110 | # Implementing readinto() and readinto1() is not strictly necessary (we |
| 1111 | # could rely on the base class that provides an implementation in terms of |
| 1112 | # read() and read1()). We do it anyway to keep the _pyio implementation |
| 1113 | # similar to the io implementation (which implements the methods for |
| 1114 | # performance reasons). |
| 1115 | def _readinto(self, buf, read1): |
| 1116 | """Read data into *buf* with at most one system call.""" |
| 1117 | |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 1118 | # Need to create a memoryview object of type 'b', otherwise |
| 1119 | # we may not be able to assign bytes to it, and slicing it |
| 1120 | # would create a new object. |
| 1121 | if not isinstance(buf, memoryview): |
| 1122 | buf = memoryview(buf) |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 1123 | if buf.nbytes == 0: |
| 1124 | return 0 |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 1125 | buf = buf.cast('B') |
| 1126 | |
| 1127 | written = 0 |
| 1128 | with self._read_lock: |
| 1129 | while written < len(buf): |
| 1130 | |
| 1131 | # First try to read from internal buffer |
| 1132 | avail = min(len(self._read_buf) - self._read_pos, len(buf)) |
| 1133 | if avail: |
| 1134 | buf[written:written+avail] = \ |
| 1135 | self._read_buf[self._read_pos:self._read_pos+avail] |
| 1136 | self._read_pos += avail |
| 1137 | written += avail |
| 1138 | if written == len(buf): |
| 1139 | break |
| 1140 | |
| 1141 | # If remaining space in callers buffer is larger than |
| 1142 | # internal buffer, read directly into callers buffer |
| 1143 | if len(buf) - written > self.buffer_size: |
| 1144 | n = self.raw.readinto(buf[written:]) |
| 1145 | if not n: |
| 1146 | break # eof |
| 1147 | written += n |
| 1148 | |
| 1149 | # Otherwise refill internal buffer - unless we're |
| 1150 | # in read1 mode and already got some data |
| 1151 | elif not (read1 and written): |
| 1152 | if not self._peek_unlocked(1): |
| 1153 | break # eof |
| 1154 | |
| 1155 | # In readinto1 mode, return as soon as we have some data |
| 1156 | if read1 and written: |
| 1157 | break |
| 1158 | |
| 1159 | return written |
| 1160 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1161 | def tell(self): |
| 1162 | return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos |
| 1163 | |
| 1164 | def seek(self, pos, whence=0): |
Jesus Cea | 9436361 | 2012-06-22 18:32:07 +0200 | [diff] [blame] | 1165 | if whence not in valid_seek_flags: |
Jesus Cea | 990eff0 | 2012-04-26 17:05:31 +0200 | [diff] [blame] | 1166 | raise ValueError("invalid whence value") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1167 | with self._read_lock: |
| 1168 | if whence == 1: |
| 1169 | pos -= len(self._read_buf) - self._read_pos |
| 1170 | pos = _BufferedIOMixin.seek(self, pos, whence) |
| 1171 | self._reset_read_buf() |
| 1172 | return pos |
| 1173 | |
| 1174 | class BufferedWriter(_BufferedIOMixin): |
| 1175 | |
| 1176 | """A buffer for a writeable sequential RawIO object. |
| 1177 | |
| 1178 | The constructor creates a BufferedWriter for the given writeable raw |
| 1179 | stream. If the buffer_size is not given, it defaults to |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1180 | DEFAULT_BUFFER_SIZE. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1181 | """ |
| 1182 | |
Florent Xicluna | 109d573 | 2012-07-07 17:03:22 +0200 | [diff] [blame] | 1183 | def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1184 | if not raw.writable(): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1185 | raise OSError('"raw" argument must be writable.') |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1186 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1187 | _BufferedIOMixin.__init__(self, raw) |
| 1188 | if buffer_size <= 0: |
| 1189 | raise ValueError("invalid buffer size") |
| 1190 | self.buffer_size = buffer_size |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1191 | self._write_buf = bytearray() |
| 1192 | self._write_lock = Lock() |
| 1193 | |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 1194 | def writable(self): |
| 1195 | return self.raw.writable() |
| 1196 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1197 | def write(self, b): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1198 | if isinstance(b, str): |
| 1199 | raise TypeError("can't write str to binary stream") |
| 1200 | with self._write_lock: |
benfogle | 9703f09 | 2017-11-10 16:03:40 -0500 | [diff] [blame] | 1201 | if self.closed: |
| 1202 | raise ValueError("write to closed file") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1203 | # XXX we can implement some more tricks to try and avoid |
| 1204 | # partial writes |
| 1205 | if len(self._write_buf) > self.buffer_size: |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 1206 | # We're full, so let's pre-flush the buffer. (This may |
| 1207 | # raise BlockingIOError with characters_written == 0.) |
| 1208 | self._flush_unlocked() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1209 | before = len(self._write_buf) |
| 1210 | self._write_buf.extend(b) |
| 1211 | written = len(self._write_buf) - before |
| 1212 | if len(self._write_buf) > self.buffer_size: |
| 1213 | try: |
| 1214 | self._flush_unlocked() |
| 1215 | except BlockingIOError as e: |
Benjamin Peterson | 394ee00 | 2009-03-05 22:33:59 +0000 | [diff] [blame] | 1216 | if len(self._write_buf) > self.buffer_size: |
| 1217 | # We've hit the buffer_size. We have to accept a partial |
| 1218 | # write and cut back our buffer. |
| 1219 | overage = len(self._write_buf) - self.buffer_size |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1220 | written -= overage |
Benjamin Peterson | 394ee00 | 2009-03-05 22:33:59 +0000 | [diff] [blame] | 1221 | self._write_buf = self._write_buf[:self.buffer_size] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1222 | raise BlockingIOError(e.errno, e.strerror, written) |
| 1223 | return written |
| 1224 | |
| 1225 | def truncate(self, pos=None): |
| 1226 | with self._write_lock: |
| 1227 | self._flush_unlocked() |
| 1228 | if pos is None: |
| 1229 | pos = self.raw.tell() |
| 1230 | return self.raw.truncate(pos) |
| 1231 | |
| 1232 | def flush(self): |
| 1233 | with self._write_lock: |
| 1234 | self._flush_unlocked() |
| 1235 | |
| 1236 | def _flush_unlocked(self): |
| 1237 | if self.closed: |
Jim Fasarakis-Hilliard | 1e73dbb | 2017-03-26 23:59:08 +0300 | [diff] [blame] | 1238 | raise ValueError("flush on closed file") |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 1239 | while self._write_buf: |
| 1240 | try: |
| 1241 | n = self.raw.write(self._write_buf) |
| 1242 | except BlockingIOError: |
| 1243 | raise RuntimeError("self.raw should implement RawIOBase: it " |
| 1244 | "should not raise BlockingIOError") |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 1245 | if n is None: |
| 1246 | raise BlockingIOError( |
| 1247 | errno.EAGAIN, |
| 1248 | "write could not complete without blocking", 0) |
| 1249 | if n > len(self._write_buf) or n < 0: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1250 | raise OSError("write() returned incorrect number of bytes") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1251 | del self._write_buf[:n] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1252 | |
| 1253 | def tell(self): |
| 1254 | return _BufferedIOMixin.tell(self) + len(self._write_buf) |
| 1255 | |
| 1256 | def seek(self, pos, whence=0): |
Jesus Cea | 9436361 | 2012-06-22 18:32:07 +0200 | [diff] [blame] | 1257 | if whence not in valid_seek_flags: |
| 1258 | raise ValueError("invalid whence value") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1259 | with self._write_lock: |
| 1260 | self._flush_unlocked() |
| 1261 | return _BufferedIOMixin.seek(self, pos, whence) |
| 1262 | |
benfogle | 9703f09 | 2017-11-10 16:03:40 -0500 | [diff] [blame] | 1263 | def close(self): |
| 1264 | with self._write_lock: |
| 1265 | if self.raw is None or self.closed: |
| 1266 | return |
| 1267 | # We have to release the lock and call self.flush() (which will |
| 1268 | # probably just re-take the lock) in case flush has been overridden in |
| 1269 | # a subclass or the user set self.flush to something. This is the same |
| 1270 | # behavior as the C implementation. |
| 1271 | try: |
| 1272 | # may raise BlockingIOError or BrokenPipeError etc |
| 1273 | self.flush() |
| 1274 | finally: |
| 1275 | with self._write_lock: |
| 1276 | self.raw.close() |
| 1277 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1278 | |
| 1279 | class BufferedRWPair(BufferedIOBase): |
| 1280 | |
| 1281 | """A buffered reader and writer object together. |
| 1282 | |
| 1283 | A buffered reader object and buffered writer object put together to |
| 1284 | form a sequential IO object that can read and write. This is typically |
| 1285 | used with a socket or two-way pipe. |
| 1286 | |
| 1287 | reader and writer are RawIOBase objects that are readable and |
| 1288 | writeable respectively. If the buffer_size is omitted it defaults to |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1289 | DEFAULT_BUFFER_SIZE. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1290 | """ |
| 1291 | |
| 1292 | # XXX The usefulness of this (compared to having two separate IO |
| 1293 | # objects) is questionable. |
| 1294 | |
Florent Xicluna | 109d573 | 2012-07-07 17:03:22 +0200 | [diff] [blame] | 1295 | def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1296 | """Constructor. |
| 1297 | |
| 1298 | The arguments are two RawIO instances. |
| 1299 | """ |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1300 | if not reader.readable(): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1301 | raise OSError('"reader" argument must be readable.') |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1302 | |
| 1303 | if not writer.writable(): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1304 | raise OSError('"writer" argument must be writable.') |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1305 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1306 | self.reader = BufferedReader(reader, buffer_size) |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1307 | self.writer = BufferedWriter(writer, buffer_size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1308 | |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 1309 | def read(self, size=-1): |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1310 | if size is None: |
| 1311 | size = -1 |
| 1312 | return self.reader.read(size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1313 | |
| 1314 | def readinto(self, b): |
| 1315 | return self.reader.readinto(b) |
| 1316 | |
| 1317 | def write(self, b): |
| 1318 | return self.writer.write(b) |
| 1319 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1320 | def peek(self, size=0): |
| 1321 | return self.reader.peek(size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1322 | |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 1323 | def read1(self, size=-1): |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1324 | return self.reader.read1(size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1325 | |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 1326 | def readinto1(self, b): |
| 1327 | return self.reader.readinto1(b) |
| 1328 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1329 | def readable(self): |
| 1330 | return self.reader.readable() |
| 1331 | |
| 1332 | def writable(self): |
| 1333 | return self.writer.writable() |
| 1334 | |
| 1335 | def flush(self): |
| 1336 | return self.writer.flush() |
| 1337 | |
| 1338 | def close(self): |
Serhiy Storchaka | 7665be6 | 2015-03-24 23:21:57 +0200 | [diff] [blame] | 1339 | try: |
| 1340 | self.writer.close() |
| 1341 | finally: |
| 1342 | self.reader.close() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1343 | |
| 1344 | def isatty(self): |
| 1345 | return self.reader.isatty() or self.writer.isatty() |
| 1346 | |
| 1347 | @property |
| 1348 | def closed(self): |
| 1349 | return self.writer.closed |
| 1350 | |
| 1351 | |
| 1352 | class BufferedRandom(BufferedWriter, BufferedReader): |
| 1353 | |
| 1354 | """A buffered interface to random access streams. |
| 1355 | |
| 1356 | The constructor creates a reader and writer for a seekable stream, |
| 1357 | raw, given in the first argument. If the buffer_size is omitted it |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1358 | defaults to DEFAULT_BUFFER_SIZE. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1359 | """ |
| 1360 | |
Florent Xicluna | 109d573 | 2012-07-07 17:03:22 +0200 | [diff] [blame] | 1361 | def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1362 | raw._checkSeekable() |
| 1363 | BufferedReader.__init__(self, raw, buffer_size) |
Florent Xicluna | 109d573 | 2012-07-07 17:03:22 +0200 | [diff] [blame] | 1364 | BufferedWriter.__init__(self, raw, buffer_size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1365 | |
| 1366 | def seek(self, pos, whence=0): |
Jesus Cea | 9436361 | 2012-06-22 18:32:07 +0200 | [diff] [blame] | 1367 | if whence not in valid_seek_flags: |
| 1368 | raise ValueError("invalid whence value") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1369 | self.flush() |
| 1370 | if self._read_buf: |
| 1371 | # Undo read ahead. |
| 1372 | with self._read_lock: |
| 1373 | self.raw.seek(self._read_pos - len(self._read_buf), 1) |
| 1374 | # First do the raw seek, then empty the read buffer, so that |
| 1375 | # if the raw seek fails, we don't lose buffered data forever. |
| 1376 | pos = self.raw.seek(pos, whence) |
| 1377 | with self._read_lock: |
| 1378 | self._reset_read_buf() |
| 1379 | if pos < 0: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1380 | raise OSError("seek() returned invalid position") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1381 | return pos |
| 1382 | |
| 1383 | def tell(self): |
| 1384 | if self._write_buf: |
| 1385 | return BufferedWriter.tell(self) |
| 1386 | else: |
| 1387 | return BufferedReader.tell(self) |
| 1388 | |
| 1389 | def truncate(self, pos=None): |
| 1390 | if pos is None: |
| 1391 | pos = self.tell() |
| 1392 | # Use seek to flush the read buffer. |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 1393 | return BufferedWriter.truncate(self, pos) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1394 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1395 | def read(self, size=None): |
| 1396 | if size is None: |
| 1397 | size = -1 |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1398 | self.flush() |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1399 | return BufferedReader.read(self, size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1400 | |
| 1401 | def readinto(self, b): |
| 1402 | self.flush() |
| 1403 | return BufferedReader.readinto(self, b) |
| 1404 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1405 | def peek(self, size=0): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1406 | self.flush() |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1407 | return BufferedReader.peek(self, size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1408 | |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 1409 | def read1(self, size=-1): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1410 | self.flush() |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1411 | return BufferedReader.read1(self, size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1412 | |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 1413 | def readinto1(self, b): |
| 1414 | self.flush() |
| 1415 | return BufferedReader.readinto1(self, b) |
| 1416 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1417 | def write(self, b): |
| 1418 | if self._read_buf: |
| 1419 | # Undo readahead |
| 1420 | with self._read_lock: |
| 1421 | self.raw.seek(self._read_pos - len(self._read_buf), 1) |
| 1422 | self._reset_read_buf() |
| 1423 | return BufferedWriter.write(self, b) |
| 1424 | |
| 1425 | |
Serhiy Storchaka | 71fd224 | 2015-04-10 16:16:16 +0300 | [diff] [blame] | 1426 | class FileIO(RawIOBase): |
| 1427 | _fd = -1 |
| 1428 | _created = False |
| 1429 | _readable = False |
| 1430 | _writable = False |
| 1431 | _appending = False |
| 1432 | _seekable = None |
| 1433 | _closefd = True |
| 1434 | |
| 1435 | def __init__(self, file, mode='r', closefd=True, opener=None): |
| 1436 | """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading, |
| 1437 | writing, exclusive creation or appending. The file will be created if it |
| 1438 | doesn't exist when opened for writing or appending; it will be truncated |
| 1439 | when opened for writing. A FileExistsError will be raised if it already |
| 1440 | exists when opened for creating. Opening a file for creating implies |
| 1441 | writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode |
| 1442 | to allow simultaneous reading and writing. A custom opener can be used by |
| 1443 | passing a callable as *opener*. The underlying file descriptor for the file |
| 1444 | object is then obtained by calling opener with (*name*, *flags*). |
| 1445 | *opener* must return an open file descriptor (passing os.open as *opener* |
| 1446 | results in functionality similar to passing None). |
| 1447 | """ |
| 1448 | if self._fd >= 0: |
| 1449 | # Have to close the existing file first. |
| 1450 | try: |
| 1451 | if self._closefd: |
| 1452 | os.close(self._fd) |
| 1453 | finally: |
| 1454 | self._fd = -1 |
| 1455 | |
| 1456 | if isinstance(file, float): |
| 1457 | raise TypeError('integer argument expected, got float') |
| 1458 | if isinstance(file, int): |
| 1459 | fd = file |
| 1460 | if fd < 0: |
| 1461 | raise ValueError('negative file descriptor') |
| 1462 | else: |
| 1463 | fd = -1 |
| 1464 | |
| 1465 | if not isinstance(mode, str): |
| 1466 | raise TypeError('invalid mode: %s' % (mode,)) |
| 1467 | if not set(mode) <= set('xrwab+'): |
| 1468 | raise ValueError('invalid mode: %s' % (mode,)) |
| 1469 | if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1: |
| 1470 | raise ValueError('Must have exactly one of create/read/write/append ' |
| 1471 | 'mode and at most one plus') |
| 1472 | |
| 1473 | if 'x' in mode: |
| 1474 | self._created = True |
| 1475 | self._writable = True |
| 1476 | flags = os.O_EXCL | os.O_CREAT |
| 1477 | elif 'r' in mode: |
| 1478 | self._readable = True |
| 1479 | flags = 0 |
| 1480 | elif 'w' in mode: |
| 1481 | self._writable = True |
| 1482 | flags = os.O_CREAT | os.O_TRUNC |
| 1483 | elif 'a' in mode: |
| 1484 | self._writable = True |
| 1485 | self._appending = True |
| 1486 | flags = os.O_APPEND | os.O_CREAT |
| 1487 | |
| 1488 | if '+' in mode: |
| 1489 | self._readable = True |
| 1490 | self._writable = True |
| 1491 | |
| 1492 | if self._readable and self._writable: |
| 1493 | flags |= os.O_RDWR |
| 1494 | elif self._readable: |
| 1495 | flags |= os.O_RDONLY |
| 1496 | else: |
| 1497 | flags |= os.O_WRONLY |
| 1498 | |
| 1499 | flags |= getattr(os, 'O_BINARY', 0) |
| 1500 | |
| 1501 | noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or |
| 1502 | getattr(os, 'O_CLOEXEC', 0)) |
| 1503 | flags |= noinherit_flag |
| 1504 | |
| 1505 | owned_fd = None |
| 1506 | try: |
| 1507 | if fd < 0: |
| 1508 | if not closefd: |
| 1509 | raise ValueError('Cannot use closefd=False with file name') |
| 1510 | if opener is None: |
| 1511 | fd = os.open(file, flags, 0o666) |
| 1512 | else: |
| 1513 | fd = opener(file, flags) |
| 1514 | if not isinstance(fd, int): |
| 1515 | raise TypeError('expected integer from opener') |
| 1516 | if fd < 0: |
| 1517 | raise OSError('Negative file descriptor') |
| 1518 | owned_fd = fd |
| 1519 | if not noinherit_flag: |
| 1520 | os.set_inheritable(fd, False) |
| 1521 | |
| 1522 | self._closefd = closefd |
| 1523 | fdfstat = os.fstat(fd) |
| 1524 | try: |
| 1525 | if stat.S_ISDIR(fdfstat.st_mode): |
| 1526 | raise IsADirectoryError(errno.EISDIR, |
| 1527 | os.strerror(errno.EISDIR), file) |
| 1528 | except AttributeError: |
| 1529 | # Ignore the AttribueError if stat.S_ISDIR or errno.EISDIR |
| 1530 | # don't exist. |
| 1531 | pass |
| 1532 | self._blksize = getattr(fdfstat, 'st_blksize', 0) |
| 1533 | if self._blksize <= 1: |
| 1534 | self._blksize = DEFAULT_BUFFER_SIZE |
| 1535 | |
| 1536 | if _setmode: |
| 1537 | # don't translate newlines (\r\n <=> \n) |
| 1538 | _setmode(fd, os.O_BINARY) |
| 1539 | |
| 1540 | self.name = file |
| 1541 | if self._appending: |
| 1542 | # For consistent behaviour, we explicitly seek to the |
| 1543 | # end of file (otherwise, it might be done only on the |
| 1544 | # first write()). |
| 1545 | os.lseek(fd, 0, SEEK_END) |
| 1546 | except: |
| 1547 | if owned_fd is not None: |
| 1548 | os.close(owned_fd) |
| 1549 | raise |
| 1550 | self._fd = fd |
| 1551 | |
| 1552 | def __del__(self): |
| 1553 | if self._fd >= 0 and self._closefd and not self.closed: |
| 1554 | import warnings |
| 1555 | warnings.warn('unclosed file %r' % (self,), ResourceWarning, |
Victor Stinner | e19558a | 2016-03-23 00:28:08 +0100 | [diff] [blame] | 1556 | stacklevel=2, source=self) |
Serhiy Storchaka | 71fd224 | 2015-04-10 16:16:16 +0300 | [diff] [blame] | 1557 | self.close() |
| 1558 | |
| 1559 | def __getstate__(self): |
Serhiy Storchaka | 0353b4e | 2018-10-31 02:28:07 +0200 | [diff] [blame] | 1560 | raise TypeError(f"cannot pickle {self.__class__.__name__!r} object") |
Serhiy Storchaka | 71fd224 | 2015-04-10 16:16:16 +0300 | [diff] [blame] | 1561 | |
| 1562 | def __repr__(self): |
| 1563 | class_name = '%s.%s' % (self.__class__.__module__, |
| 1564 | self.__class__.__qualname__) |
| 1565 | if self.closed: |
| 1566 | return '<%s [closed]>' % class_name |
| 1567 | try: |
| 1568 | name = self.name |
| 1569 | except AttributeError: |
| 1570 | return ('<%s fd=%d mode=%r closefd=%r>' % |
| 1571 | (class_name, self._fd, self.mode, self._closefd)) |
| 1572 | else: |
| 1573 | return ('<%s name=%r mode=%r closefd=%r>' % |
| 1574 | (class_name, name, self.mode, self._closefd)) |
| 1575 | |
| 1576 | def _checkReadable(self): |
| 1577 | if not self._readable: |
| 1578 | raise UnsupportedOperation('File not open for reading') |
| 1579 | |
| 1580 | def _checkWritable(self, msg=None): |
| 1581 | if not self._writable: |
| 1582 | raise UnsupportedOperation('File not open for writing') |
| 1583 | |
| 1584 | def read(self, size=None): |
| 1585 | """Read at most size bytes, returned as bytes. |
| 1586 | |
| 1587 | Only makes one system call, so less data may be returned than requested |
| 1588 | In non-blocking mode, returns None if no data is available. |
| 1589 | Return an empty bytes object at EOF. |
| 1590 | """ |
| 1591 | self._checkClosed() |
| 1592 | self._checkReadable() |
| 1593 | if size is None or size < 0: |
| 1594 | return self.readall() |
| 1595 | try: |
| 1596 | return os.read(self._fd, size) |
| 1597 | except BlockingIOError: |
| 1598 | return None |
| 1599 | |
| 1600 | def readall(self): |
| 1601 | """Read all data from the file, returned as bytes. |
| 1602 | |
| 1603 | In non-blocking mode, returns as much as is immediately available, |
| 1604 | or None if no data is available. Return an empty bytes object at EOF. |
| 1605 | """ |
| 1606 | self._checkClosed() |
| 1607 | self._checkReadable() |
| 1608 | bufsize = DEFAULT_BUFFER_SIZE |
| 1609 | try: |
| 1610 | pos = os.lseek(self._fd, 0, SEEK_CUR) |
| 1611 | end = os.fstat(self._fd).st_size |
| 1612 | if end >= pos: |
| 1613 | bufsize = end - pos + 1 |
| 1614 | except OSError: |
| 1615 | pass |
| 1616 | |
| 1617 | result = bytearray() |
| 1618 | while True: |
| 1619 | if len(result) >= bufsize: |
| 1620 | bufsize = len(result) |
| 1621 | bufsize += max(bufsize, DEFAULT_BUFFER_SIZE) |
| 1622 | n = bufsize - len(result) |
| 1623 | try: |
| 1624 | chunk = os.read(self._fd, n) |
| 1625 | except BlockingIOError: |
| 1626 | if result: |
| 1627 | break |
| 1628 | return None |
| 1629 | if not chunk: # reached the end of the file |
| 1630 | break |
| 1631 | result += chunk |
| 1632 | |
| 1633 | return bytes(result) |
| 1634 | |
| 1635 | def readinto(self, b): |
| 1636 | """Same as RawIOBase.readinto().""" |
| 1637 | m = memoryview(b).cast('B') |
| 1638 | data = self.read(len(m)) |
| 1639 | n = len(data) |
| 1640 | m[:n] = data |
| 1641 | return n |
| 1642 | |
| 1643 | def write(self, b): |
| 1644 | """Write bytes b to file, return number written. |
| 1645 | |
| 1646 | Only makes one system call, so not all of the data may be written. |
| 1647 | The number of bytes actually written is returned. In non-blocking mode, |
| 1648 | returns None if the write would block. |
| 1649 | """ |
| 1650 | self._checkClosed() |
| 1651 | self._checkWritable() |
| 1652 | try: |
| 1653 | return os.write(self._fd, b) |
| 1654 | except BlockingIOError: |
| 1655 | return None |
| 1656 | |
| 1657 | def seek(self, pos, whence=SEEK_SET): |
| 1658 | """Move to new file position. |
| 1659 | |
| 1660 | Argument offset is a byte count. Optional argument whence defaults to |
| 1661 | SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values |
| 1662 | are SEEK_CUR or 1 (move relative to current position, positive or negative), |
| 1663 | and SEEK_END or 2 (move relative to end of file, usually negative, although |
| 1664 | many platforms allow seeking beyond the end of a file). |
| 1665 | |
| 1666 | Note that not all file objects are seekable. |
| 1667 | """ |
| 1668 | if isinstance(pos, float): |
| 1669 | raise TypeError('an integer is required') |
| 1670 | self._checkClosed() |
| 1671 | return os.lseek(self._fd, pos, whence) |
| 1672 | |
| 1673 | def tell(self): |
| 1674 | """tell() -> int. Current file position. |
| 1675 | |
| 1676 | Can raise OSError for non seekable files.""" |
| 1677 | self._checkClosed() |
| 1678 | return os.lseek(self._fd, 0, SEEK_CUR) |
| 1679 | |
| 1680 | def truncate(self, size=None): |
| 1681 | """Truncate the file to at most size bytes. |
| 1682 | |
| 1683 | Size defaults to the current file position, as returned by tell(). |
| 1684 | The current file position is changed to the value of size. |
| 1685 | """ |
| 1686 | self._checkClosed() |
| 1687 | self._checkWritable() |
| 1688 | if size is None: |
| 1689 | size = self.tell() |
| 1690 | os.ftruncate(self._fd, size) |
| 1691 | return size |
| 1692 | |
| 1693 | def close(self): |
| 1694 | """Close the file. |
| 1695 | |
| 1696 | A closed file cannot be used for further I/O operations. close() may be |
| 1697 | called more than once without error. |
| 1698 | """ |
| 1699 | if not self.closed: |
| 1700 | try: |
| 1701 | if self._closefd: |
| 1702 | os.close(self._fd) |
| 1703 | finally: |
| 1704 | super().close() |
| 1705 | |
| 1706 | def seekable(self): |
| 1707 | """True if file supports random-access.""" |
| 1708 | self._checkClosed() |
| 1709 | if self._seekable is None: |
| 1710 | try: |
| 1711 | self.tell() |
| 1712 | except OSError: |
| 1713 | self._seekable = False |
| 1714 | else: |
| 1715 | self._seekable = True |
| 1716 | return self._seekable |
| 1717 | |
| 1718 | def readable(self): |
| 1719 | """True if file was opened in a read mode.""" |
| 1720 | self._checkClosed() |
| 1721 | return self._readable |
| 1722 | |
| 1723 | def writable(self): |
| 1724 | """True if file was opened in a write mode.""" |
| 1725 | self._checkClosed() |
| 1726 | return self._writable |
| 1727 | |
| 1728 | def fileno(self): |
| 1729 | """Return the underlying file descriptor (an integer).""" |
| 1730 | self._checkClosed() |
| 1731 | return self._fd |
| 1732 | |
| 1733 | def isatty(self): |
| 1734 | """True if the file is connected to a TTY device.""" |
| 1735 | self._checkClosed() |
| 1736 | return os.isatty(self._fd) |
| 1737 | |
| 1738 | @property |
| 1739 | def closefd(self): |
| 1740 | """True if the file descriptor will be closed by close().""" |
| 1741 | return self._closefd |
| 1742 | |
| 1743 | @property |
| 1744 | def mode(self): |
| 1745 | """String giving the file mode""" |
| 1746 | if self._created: |
| 1747 | if self._readable: |
| 1748 | return 'xb+' |
| 1749 | else: |
| 1750 | return 'xb' |
| 1751 | elif self._appending: |
| 1752 | if self._readable: |
| 1753 | return 'ab+' |
| 1754 | else: |
| 1755 | return 'ab' |
| 1756 | elif self._readable: |
| 1757 | if self._writable: |
| 1758 | return 'rb+' |
| 1759 | else: |
| 1760 | return 'rb' |
| 1761 | else: |
| 1762 | return 'wb' |
| 1763 | |
| 1764 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1765 | class TextIOBase(IOBase): |
| 1766 | |
| 1767 | """Base class for text I/O. |
| 1768 | |
| 1769 | This class provides a character and line based interface to stream |
Steve Palmer | 7b97ab3 | 2019-04-09 05:35:27 +0100 | [diff] [blame] | 1770 | I/O. There is no public constructor. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1771 | """ |
| 1772 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1773 | def read(self, size=-1): |
| 1774 | """Read at most size characters from stream, where size is an int. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1775 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 1776 | Read from underlying buffer until we have size characters or we hit EOF. |
| 1777 | If size is negative or omitted, read until EOF. |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 1778 | |
| 1779 | Returns a string. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1780 | """ |
| 1781 | self._unsupported("read") |
| 1782 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 1783 | def write(self, s): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 1784 | """Write string s to stream and returning an int.""" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1785 | self._unsupported("write") |
| 1786 | |
Georg Brandl | 4d73b57 | 2011-01-13 07:13:06 +0000 | [diff] [blame] | 1787 | def truncate(self, pos=None): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 1788 | """Truncate size to pos, where pos is an int.""" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1789 | self._unsupported("truncate") |
| 1790 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 1791 | def readline(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1792 | """Read until newline or EOF. |
| 1793 | |
| 1794 | Returns an empty string if EOF is hit immediately. |
| 1795 | """ |
| 1796 | self._unsupported("readline") |
| 1797 | |
Raymond Hettinger | 3c94024 | 2011-01-12 23:39:31 +0000 | [diff] [blame] | 1798 | def detach(self): |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 1799 | """ |
| 1800 | Separate the underlying buffer from the TextIOBase and return it. |
| 1801 | |
| 1802 | After the underlying buffer has been detached, the TextIO is in an |
| 1803 | unusable state. |
| 1804 | """ |
| 1805 | self._unsupported("detach") |
| 1806 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1807 | @property |
| 1808 | def encoding(self): |
| 1809 | """Subclasses should override.""" |
| 1810 | return None |
| 1811 | |
| 1812 | @property |
| 1813 | def newlines(self): |
| 1814 | """Line endings translated so far. |
| 1815 | |
| 1816 | Only line endings translated during reading are considered. |
| 1817 | |
| 1818 | Subclasses should override. |
| 1819 | """ |
| 1820 | return None |
| 1821 | |
Benjamin Peterson | 0926ad1 | 2009-06-06 18:02:12 +0000 | [diff] [blame] | 1822 | @property |
| 1823 | def errors(self): |
| 1824 | """Error setting of the decoder or encoder. |
| 1825 | |
| 1826 | Subclasses should override.""" |
| 1827 | return None |
| 1828 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1829 | io.TextIOBase.register(TextIOBase) |
| 1830 | |
| 1831 | |
| 1832 | class IncrementalNewlineDecoder(codecs.IncrementalDecoder): |
| 1833 | r"""Codec used when reading a file in universal newlines mode. It wraps |
| 1834 | another incremental decoder, translating \r\n and \r into \n. It also |
| 1835 | records the types of newlines encountered. When used with |
| 1836 | translate=False, it ensures that the newline sequence is returned in |
| 1837 | one piece. |
| 1838 | """ |
| 1839 | def __init__(self, decoder, translate, errors='strict'): |
| 1840 | codecs.IncrementalDecoder.__init__(self, errors=errors) |
| 1841 | self.translate = translate |
| 1842 | self.decoder = decoder |
| 1843 | self.seennl = 0 |
| 1844 | self.pendingcr = False |
| 1845 | |
| 1846 | def decode(self, input, final=False): |
| 1847 | # decode input (with the eventual \r from a previous pass) |
| 1848 | if self.decoder is None: |
| 1849 | output = input |
| 1850 | else: |
| 1851 | output = self.decoder.decode(input, final=final) |
| 1852 | if self.pendingcr and (output or final): |
| 1853 | output = "\r" + output |
| 1854 | self.pendingcr = False |
| 1855 | |
| 1856 | # retain last \r even when not translating data: |
| 1857 | # then readline() is sure to get \r\n in one pass |
| 1858 | if output.endswith("\r") and not final: |
| 1859 | output = output[:-1] |
| 1860 | self.pendingcr = True |
| 1861 | |
| 1862 | # Record which newlines are read |
| 1863 | crlf = output.count('\r\n') |
| 1864 | cr = output.count('\r') - crlf |
| 1865 | lf = output.count('\n') - crlf |
| 1866 | self.seennl |= (lf and self._LF) | (cr and self._CR) \ |
| 1867 | | (crlf and self._CRLF) |
| 1868 | |
| 1869 | if self.translate: |
| 1870 | if crlf: |
| 1871 | output = output.replace("\r\n", "\n") |
| 1872 | if cr: |
| 1873 | output = output.replace("\r", "\n") |
| 1874 | |
| 1875 | return output |
| 1876 | |
| 1877 | def getstate(self): |
| 1878 | if self.decoder is None: |
| 1879 | buf = b"" |
| 1880 | flag = 0 |
| 1881 | else: |
| 1882 | buf, flag = self.decoder.getstate() |
| 1883 | flag <<= 1 |
| 1884 | if self.pendingcr: |
| 1885 | flag |= 1 |
| 1886 | return buf, flag |
| 1887 | |
| 1888 | def setstate(self, state): |
| 1889 | buf, flag = state |
| 1890 | self.pendingcr = bool(flag & 1) |
| 1891 | if self.decoder is not None: |
| 1892 | self.decoder.setstate((buf, flag >> 1)) |
| 1893 | |
| 1894 | def reset(self): |
| 1895 | self.seennl = 0 |
| 1896 | self.pendingcr = False |
| 1897 | if self.decoder is not None: |
| 1898 | self.decoder.reset() |
| 1899 | |
| 1900 | _LF = 1 |
| 1901 | _CR = 2 |
| 1902 | _CRLF = 4 |
| 1903 | |
| 1904 | @property |
| 1905 | def newlines(self): |
| 1906 | return (None, |
| 1907 | "\n", |
| 1908 | "\r", |
| 1909 | ("\r", "\n"), |
| 1910 | "\r\n", |
| 1911 | ("\n", "\r\n"), |
| 1912 | ("\r", "\r\n"), |
| 1913 | ("\r", "\n", "\r\n") |
| 1914 | )[self.seennl] |
| 1915 | |
| 1916 | |
| 1917 | class TextIOWrapper(TextIOBase): |
| 1918 | |
| 1919 | r"""Character and line based layer over a BufferedIOBase object, buffer. |
| 1920 | |
| 1921 | encoding gives the name of the encoding that the stream will be |
Victor Stinner | f86a5e8 | 2012-06-05 13:43:22 +0200 | [diff] [blame] | 1922 | decoded or encoded with. It defaults to locale.getpreferredencoding(False). |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1923 | |
| 1924 | errors determines the strictness of encoding and decoding (see the |
| 1925 | codecs.register) and defaults to "strict". |
| 1926 | |
| 1927 | newline can be None, '', '\n', '\r', or '\r\n'. It controls the |
| 1928 | handling of line endings. If it is None, universal newlines is |
| 1929 | enabled. With this enabled, on input, the lines endings '\n', '\r', |
| 1930 | or '\r\n' are translated to '\n' before being returned to the |
| 1931 | caller. Conversely, on output, '\n' is translated to the system |
Éric Araujo | 3924230 | 2011-11-03 00:08:48 +0100 | [diff] [blame] | 1932 | default line separator, os.linesep. If newline is any other of its |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1933 | legal values, that newline becomes the newline when the file is read |
| 1934 | and it is returned untranslated. On output, '\n' is converted to the |
| 1935 | newline. |
| 1936 | |
| 1937 | If line_buffering is True, a call to flush is implied when a call to |
| 1938 | write contains a newline character. |
| 1939 | """ |
| 1940 | |
| 1941 | _CHUNK_SIZE = 2048 |
| 1942 | |
Andrew Svetlov | 4e9e9c1 | 2012-08-13 16:09:54 +0300 | [diff] [blame] | 1943 | # The write_through argument has no effect here since this |
| 1944 | # implementation always writes through. The argument is present only |
| 1945 | # so that the signature can match the signature of the C version. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1946 | def __init__(self, buffer, encoding=None, errors=None, newline=None, |
Antoine Pitrou | e96ec68 | 2011-07-23 21:46:35 +0200 | [diff] [blame] | 1947 | line_buffering=False, write_through=False): |
INADA Naoki | 507434f | 2017-12-21 09:59:53 +0900 | [diff] [blame] | 1948 | self._check_newline(newline) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1949 | if encoding is None: |
| 1950 | try: |
| 1951 | encoding = os.device_encoding(buffer.fileno()) |
| 1952 | except (AttributeError, UnsupportedOperation): |
| 1953 | pass |
| 1954 | if encoding is None: |
| 1955 | try: |
| 1956 | import locale |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 1957 | except ImportError: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1958 | # Importing locale may fail if Python is being built |
| 1959 | encoding = "ascii" |
| 1960 | else: |
Victor Stinner | f86a5e8 | 2012-06-05 13:43:22 +0200 | [diff] [blame] | 1961 | encoding = locale.getpreferredencoding(False) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1962 | |
| 1963 | if not isinstance(encoding, str): |
| 1964 | raise ValueError("invalid encoding: %r" % encoding) |
| 1965 | |
Nick Coghlan | a9b1524 | 2014-02-04 22:11:18 +1000 | [diff] [blame] | 1966 | if not codecs.lookup(encoding)._is_text_encoding: |
| 1967 | msg = ("%r is not a text encoding; " |
| 1968 | "use codecs.open() to handle arbitrary codecs") |
| 1969 | raise LookupError(msg % encoding) |
| 1970 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1971 | if errors is None: |
| 1972 | errors = "strict" |
| 1973 | else: |
| 1974 | if not isinstance(errors, str): |
| 1975 | raise ValueError("invalid errors: %r" % errors) |
| 1976 | |
Antoine Pitrou | 7f8f418 | 2010-12-21 21:20:59 +0000 | [diff] [blame] | 1977 | self._buffer = buffer |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1978 | self._decoded_chars = '' # buffer for text returned from decoder |
| 1979 | self._decoded_chars_used = 0 # offset into _decoded_chars for read() |
| 1980 | self._snapshot = None # info for reconstructing decoder state |
| 1981 | self._seekable = self._telling = self.buffer.seekable() |
Antoine Pitrou | e96ec68 | 2011-07-23 21:46:35 +0200 | [diff] [blame] | 1982 | self._has_read1 = hasattr(self.buffer, 'read1') |
INADA Naoki | 507434f | 2017-12-21 09:59:53 +0900 | [diff] [blame] | 1983 | self._configure(encoding, errors, newline, |
| 1984 | line_buffering, write_through) |
| 1985 | |
| 1986 | def _check_newline(self, newline): |
| 1987 | if newline is not None and not isinstance(newline, str): |
| 1988 | raise TypeError("illegal newline type: %r" % (type(newline),)) |
| 1989 | if newline not in (None, "", "\n", "\r", "\r\n"): |
| 1990 | raise ValueError("illegal newline value: %r" % (newline,)) |
| 1991 | |
| 1992 | def _configure(self, encoding=None, errors=None, newline=None, |
| 1993 | line_buffering=False, write_through=False): |
| 1994 | self._encoding = encoding |
| 1995 | self._errors = errors |
| 1996 | self._encoder = None |
| 1997 | self._decoder = None |
Antoine Pitrou | 211b81d | 2011-02-25 20:27:33 +0000 | [diff] [blame] | 1998 | self._b2cratio = 0.0 |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1999 | |
INADA Naoki | 507434f | 2017-12-21 09:59:53 +0900 | [diff] [blame] | 2000 | self._readuniversal = not newline |
| 2001 | self._readtranslate = newline is None |
| 2002 | self._readnl = newline |
| 2003 | self._writetranslate = newline != '' |
| 2004 | self._writenl = newline or os.linesep |
| 2005 | |
| 2006 | self._line_buffering = line_buffering |
| 2007 | self._write_through = write_through |
| 2008 | |
| 2009 | # don't write a BOM in the middle of a file |
Antoine Pitrou | e450185 | 2009-05-14 18:55:55 +0000 | [diff] [blame] | 2010 | if self._seekable and self.writable(): |
| 2011 | position = self.buffer.tell() |
| 2012 | if position != 0: |
| 2013 | try: |
| 2014 | self._get_encoder().setstate(0) |
| 2015 | except LookupError: |
| 2016 | # Sometimes the encoder doesn't exist |
| 2017 | pass |
| 2018 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2019 | # self._snapshot is either None, or a tuple (dec_flags, next_input) |
| 2020 | # where dec_flags is the second (integer) item of the decoder state |
| 2021 | # and next_input is the chunk of input bytes that comes next after the |
| 2022 | # snapshot point. We use this to reconstruct decoder states in tell(). |
| 2023 | |
| 2024 | # Naming convention: |
| 2025 | # - "bytes_..." for integer variables that count input bytes |
| 2026 | # - "chars_..." for integer variables that count decoded characters |
| 2027 | |
Benjamin Peterson | c4c0eae | 2009-03-09 00:07:03 +0000 | [diff] [blame] | 2028 | def __repr__(self): |
Serhiy Storchaka | 465e60e | 2014-07-25 23:36:00 +0300 | [diff] [blame] | 2029 | result = "<{}.{}".format(self.__class__.__module__, |
| 2030 | self.__class__.__qualname__) |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 2031 | try: |
| 2032 | name = self.name |
Benjamin Peterson | 10e76b6 | 2014-12-21 20:51:50 -0600 | [diff] [blame] | 2033 | except Exception: |
Antoine Pitrou | a4815ca | 2011-01-09 20:38:15 +0000 | [diff] [blame] | 2034 | pass |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 2035 | else: |
Antoine Pitrou | a4815ca | 2011-01-09 20:38:15 +0000 | [diff] [blame] | 2036 | result += " name={0!r}".format(name) |
| 2037 | try: |
| 2038 | mode = self.mode |
Benjamin Peterson | 10e76b6 | 2014-12-21 20:51:50 -0600 | [diff] [blame] | 2039 | except Exception: |
Antoine Pitrou | a4815ca | 2011-01-09 20:38:15 +0000 | [diff] [blame] | 2040 | pass |
| 2041 | else: |
| 2042 | result += " mode={0!r}".format(mode) |
| 2043 | return result + " encoding={0!r}>".format(self.encoding) |
Benjamin Peterson | c4c0eae | 2009-03-09 00:07:03 +0000 | [diff] [blame] | 2044 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2045 | @property |
| 2046 | def encoding(self): |
| 2047 | return self._encoding |
| 2048 | |
| 2049 | @property |
| 2050 | def errors(self): |
| 2051 | return self._errors |
| 2052 | |
| 2053 | @property |
| 2054 | def line_buffering(self): |
| 2055 | return self._line_buffering |
| 2056 | |
Antoine Pitrou | 7f8f418 | 2010-12-21 21:20:59 +0000 | [diff] [blame] | 2057 | @property |
Antoine Pitrou | 3c2817b | 2017-06-03 12:32:28 +0200 | [diff] [blame] | 2058 | def write_through(self): |
| 2059 | return self._write_through |
| 2060 | |
| 2061 | @property |
Antoine Pitrou | 7f8f418 | 2010-12-21 21:20:59 +0000 | [diff] [blame] | 2062 | def buffer(self): |
| 2063 | return self._buffer |
| 2064 | |
INADA Naoki | 507434f | 2017-12-21 09:59:53 +0900 | [diff] [blame] | 2065 | def reconfigure(self, *, |
| 2066 | encoding=None, errors=None, newline=Ellipsis, |
| 2067 | line_buffering=None, write_through=None): |
Antoine Pitrou | 3c2817b | 2017-06-03 12:32:28 +0200 | [diff] [blame] | 2068 | """Reconfigure the text stream with new parameters. |
| 2069 | |
| 2070 | This also flushes the stream. |
| 2071 | """ |
INADA Naoki | 507434f | 2017-12-21 09:59:53 +0900 | [diff] [blame] | 2072 | if (self._decoder is not None |
| 2073 | and (encoding is not None or errors is not None |
| 2074 | or newline is not Ellipsis)): |
| 2075 | raise UnsupportedOperation( |
| 2076 | "It is not possible to set the encoding or newline of stream " |
| 2077 | "after the first read") |
| 2078 | |
| 2079 | if errors is None: |
| 2080 | if encoding is None: |
| 2081 | errors = self._errors |
| 2082 | else: |
| 2083 | errors = 'strict' |
| 2084 | elif not isinstance(errors, str): |
| 2085 | raise TypeError("invalid errors: %r" % errors) |
| 2086 | |
| 2087 | if encoding is None: |
| 2088 | encoding = self._encoding |
| 2089 | else: |
| 2090 | if not isinstance(encoding, str): |
| 2091 | raise TypeError("invalid encoding: %r" % encoding) |
| 2092 | |
| 2093 | if newline is Ellipsis: |
| 2094 | newline = self._readnl |
| 2095 | self._check_newline(newline) |
| 2096 | |
Antoine Pitrou | 3c2817b | 2017-06-03 12:32:28 +0200 | [diff] [blame] | 2097 | if line_buffering is None: |
| 2098 | line_buffering = self.line_buffering |
| 2099 | if write_through is None: |
| 2100 | write_through = self.write_through |
INADA Naoki | 507434f | 2017-12-21 09:59:53 +0900 | [diff] [blame] | 2101 | |
Antoine Pitrou | 3c2817b | 2017-06-03 12:32:28 +0200 | [diff] [blame] | 2102 | self.flush() |
INADA Naoki | 507434f | 2017-12-21 09:59:53 +0900 | [diff] [blame] | 2103 | self._configure(encoding, errors, newline, |
| 2104 | line_buffering, write_through) |
Antoine Pitrou | 3c2817b | 2017-06-03 12:32:28 +0200 | [diff] [blame] | 2105 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2106 | def seekable(self): |
Antoine Pitrou | 1d85745 | 2012-09-05 20:11:49 +0200 | [diff] [blame] | 2107 | if self.closed: |
| 2108 | raise ValueError("I/O operation on closed file.") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2109 | return self._seekable |
| 2110 | |
| 2111 | def readable(self): |
| 2112 | return self.buffer.readable() |
| 2113 | |
| 2114 | def writable(self): |
| 2115 | return self.buffer.writable() |
| 2116 | |
| 2117 | def flush(self): |
| 2118 | self.buffer.flush() |
| 2119 | self._telling = self._seekable |
| 2120 | |
| 2121 | def close(self): |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 2122 | if self.buffer is not None and not self.closed: |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 2123 | try: |
| 2124 | self.flush() |
| 2125 | finally: |
| 2126 | self.buffer.close() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2127 | |
| 2128 | @property |
| 2129 | def closed(self): |
| 2130 | return self.buffer.closed |
| 2131 | |
| 2132 | @property |
| 2133 | def name(self): |
| 2134 | return self.buffer.name |
| 2135 | |
| 2136 | def fileno(self): |
| 2137 | return self.buffer.fileno() |
| 2138 | |
| 2139 | def isatty(self): |
| 2140 | return self.buffer.isatty() |
| 2141 | |
Raymond Hettinger | 00fa039 | 2011-01-13 02:52:26 +0000 | [diff] [blame] | 2142 | def write(self, s): |
Raymond Hettinger | cbb8089 | 2011-01-13 18:15:51 +0000 | [diff] [blame] | 2143 | 'Write data, where s is a str' |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2144 | if self.closed: |
| 2145 | raise ValueError("write to closed file") |
| 2146 | if not isinstance(s, str): |
| 2147 | raise TypeError("can't write %s to text stream" % |
| 2148 | s.__class__.__name__) |
| 2149 | length = len(s) |
| 2150 | haslf = (self._writetranslate or self._line_buffering) and "\n" in s |
| 2151 | if haslf and self._writetranslate and self._writenl != "\n": |
| 2152 | s = s.replace("\n", self._writenl) |
| 2153 | encoder = self._encoder or self._get_encoder() |
| 2154 | # XXX What if we were just reading? |
| 2155 | b = encoder.encode(s) |
| 2156 | self.buffer.write(b) |
| 2157 | if self._line_buffering and (haslf or "\r" in s): |
| 2158 | self.flush() |
Zackery Spytz | 23db935 | 2018-06-29 04:14:58 -0600 | [diff] [blame] | 2159 | self._set_decoded_chars('') |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2160 | self._snapshot = None |
| 2161 | if self._decoder: |
| 2162 | self._decoder.reset() |
| 2163 | return length |
| 2164 | |
| 2165 | def _get_encoder(self): |
| 2166 | make_encoder = codecs.getincrementalencoder(self._encoding) |
| 2167 | self._encoder = make_encoder(self._errors) |
| 2168 | return self._encoder |
| 2169 | |
| 2170 | def _get_decoder(self): |
| 2171 | make_decoder = codecs.getincrementaldecoder(self._encoding) |
| 2172 | decoder = make_decoder(self._errors) |
| 2173 | if self._readuniversal: |
| 2174 | decoder = IncrementalNewlineDecoder(decoder, self._readtranslate) |
| 2175 | self._decoder = decoder |
| 2176 | return decoder |
| 2177 | |
| 2178 | # The following three methods implement an ADT for _decoded_chars. |
| 2179 | # Text returned from the decoder is buffered here until the client |
| 2180 | # requests it by calling our read() or readline() method. |
| 2181 | def _set_decoded_chars(self, chars): |
| 2182 | """Set the _decoded_chars buffer.""" |
| 2183 | self._decoded_chars = chars |
| 2184 | self._decoded_chars_used = 0 |
| 2185 | |
| 2186 | def _get_decoded_chars(self, n=None): |
| 2187 | """Advance into the _decoded_chars buffer.""" |
| 2188 | offset = self._decoded_chars_used |
| 2189 | if n is None: |
| 2190 | chars = self._decoded_chars[offset:] |
| 2191 | else: |
| 2192 | chars = self._decoded_chars[offset:offset + n] |
| 2193 | self._decoded_chars_used += len(chars) |
| 2194 | return chars |
| 2195 | |
| 2196 | def _rewind_decoded_chars(self, n): |
| 2197 | """Rewind the _decoded_chars buffer.""" |
| 2198 | if self._decoded_chars_used < n: |
| 2199 | raise AssertionError("rewind decoded_chars out of bounds") |
| 2200 | self._decoded_chars_used -= n |
| 2201 | |
| 2202 | def _read_chunk(self): |
| 2203 | """ |
| 2204 | Read and decode the next chunk of data from the BufferedReader. |
| 2205 | """ |
| 2206 | |
| 2207 | # The return value is True unless EOF was reached. The decoded |
| 2208 | # string is placed in self._decoded_chars (replacing its previous |
| 2209 | # value). The entire input chunk is sent to the decoder, though |
| 2210 | # some of it may remain buffered in the decoder, yet to be |
| 2211 | # converted. |
| 2212 | |
| 2213 | if self._decoder is None: |
| 2214 | raise ValueError("no decoder") |
| 2215 | |
| 2216 | if self._telling: |
| 2217 | # To prepare for tell(), we need to snapshot a point in the |
| 2218 | # file where the decoder's input buffer is empty. |
| 2219 | |
| 2220 | dec_buffer, dec_flags = self._decoder.getstate() |
| 2221 | # Given this, we know there was a valid snapshot point |
| 2222 | # len(dec_buffer) bytes ago with decoder state (b'', dec_flags). |
| 2223 | |
| 2224 | # Read a chunk, decode it, and put the result in self._decoded_chars. |
Antoine Pitrou | e96ec68 | 2011-07-23 21:46:35 +0200 | [diff] [blame] | 2225 | if self._has_read1: |
| 2226 | input_chunk = self.buffer.read1(self._CHUNK_SIZE) |
| 2227 | else: |
| 2228 | input_chunk = self.buffer.read(self._CHUNK_SIZE) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2229 | eof = not input_chunk |
Antoine Pitrou | 211b81d | 2011-02-25 20:27:33 +0000 | [diff] [blame] | 2230 | decoded_chars = self._decoder.decode(input_chunk, eof) |
| 2231 | self._set_decoded_chars(decoded_chars) |
| 2232 | if decoded_chars: |
| 2233 | self._b2cratio = len(input_chunk) / len(self._decoded_chars) |
| 2234 | else: |
| 2235 | self._b2cratio = 0.0 |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2236 | |
| 2237 | if self._telling: |
| 2238 | # At the snapshot point, len(dec_buffer) bytes before the read, |
| 2239 | # the next input to be decoded is dec_buffer + input_chunk. |
| 2240 | self._snapshot = (dec_flags, dec_buffer + input_chunk) |
| 2241 | |
| 2242 | return not eof |
| 2243 | |
| 2244 | def _pack_cookie(self, position, dec_flags=0, |
| 2245 | bytes_to_feed=0, need_eof=0, chars_to_skip=0): |
| 2246 | # The meaning of a tell() cookie is: seek to position, set the |
| 2247 | # decoder flags to dec_flags, read bytes_to_feed bytes, feed them |
| 2248 | # into the decoder with need_eof as the EOF flag, then skip |
| 2249 | # chars_to_skip characters of the decoded result. For most simple |
| 2250 | # decoders, tell() will often just give a byte offset in the file. |
| 2251 | return (position | (dec_flags<<64) | (bytes_to_feed<<128) | |
| 2252 | (chars_to_skip<<192) | bool(need_eof)<<256) |
| 2253 | |
| 2254 | def _unpack_cookie(self, bigint): |
| 2255 | rest, position = divmod(bigint, 1<<64) |
| 2256 | rest, dec_flags = divmod(rest, 1<<64) |
| 2257 | rest, bytes_to_feed = divmod(rest, 1<<64) |
| 2258 | need_eof, chars_to_skip = divmod(rest, 1<<64) |
| 2259 | return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip |
| 2260 | |
| 2261 | def tell(self): |
| 2262 | if not self._seekable: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 2263 | raise UnsupportedOperation("underlying stream is not seekable") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2264 | if not self._telling: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 2265 | raise OSError("telling position disabled by next() call") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2266 | self.flush() |
| 2267 | position = self.buffer.tell() |
| 2268 | decoder = self._decoder |
| 2269 | if decoder is None or self._snapshot is None: |
| 2270 | if self._decoded_chars: |
| 2271 | # This should never happen. |
| 2272 | raise AssertionError("pending decoded text") |
| 2273 | return position |
| 2274 | |
| 2275 | # Skip backward to the snapshot point (see _read_chunk). |
| 2276 | dec_flags, next_input = self._snapshot |
| 2277 | position -= len(next_input) |
| 2278 | |
| 2279 | # How many decoded characters have been used up since the snapshot? |
| 2280 | chars_to_skip = self._decoded_chars_used |
| 2281 | if chars_to_skip == 0: |
| 2282 | # We haven't moved from the snapshot point. |
| 2283 | return self._pack_cookie(position, dec_flags) |
| 2284 | |
| 2285 | # Starting from the snapshot position, we will walk the decoder |
| 2286 | # forward until it gives us enough decoded characters. |
| 2287 | saved_state = decoder.getstate() |
| 2288 | try: |
Antoine Pitrou | 211b81d | 2011-02-25 20:27:33 +0000 | [diff] [blame] | 2289 | # Fast search for an acceptable start point, close to our |
| 2290 | # current pos. |
| 2291 | # Rationale: calling decoder.decode() has a large overhead |
| 2292 | # regardless of chunk size; we want the number of such calls to |
Raymond Hettinger | 1401018 | 2018-09-13 21:17:40 -0700 | [diff] [blame] | 2293 | # be O(1) in most situations (common decoders, sensible input). |
Antoine Pitrou | 211b81d | 2011-02-25 20:27:33 +0000 | [diff] [blame] | 2294 | # Actually, it will be exactly 1 for fixed-size codecs (all |
| 2295 | # 8-bit codecs, also UTF-16 and UTF-32). |
| 2296 | skip_bytes = int(self._b2cratio * chars_to_skip) |
| 2297 | skip_back = 1 |
| 2298 | assert skip_bytes <= len(next_input) |
| 2299 | while skip_bytes > 0: |
| 2300 | decoder.setstate((b'', dec_flags)) |
| 2301 | # Decode up to temptative start point |
| 2302 | n = len(decoder.decode(next_input[:skip_bytes])) |
| 2303 | if n <= chars_to_skip: |
| 2304 | b, d = decoder.getstate() |
| 2305 | if not b: |
| 2306 | # Before pos and no bytes buffered in decoder => OK |
| 2307 | dec_flags = d |
| 2308 | chars_to_skip -= n |
| 2309 | break |
| 2310 | # Skip back by buffered amount and reset heuristic |
| 2311 | skip_bytes -= len(b) |
| 2312 | skip_back = 1 |
| 2313 | else: |
| 2314 | # We're too far ahead, skip back a bit |
| 2315 | skip_bytes -= skip_back |
| 2316 | skip_back = skip_back * 2 |
| 2317 | else: |
| 2318 | skip_bytes = 0 |
| 2319 | decoder.setstate((b'', dec_flags)) |
| 2320 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2321 | # Note our initial start point. |
Antoine Pitrou | 211b81d | 2011-02-25 20:27:33 +0000 | [diff] [blame] | 2322 | start_pos = position + skip_bytes |
| 2323 | start_flags = dec_flags |
| 2324 | if chars_to_skip == 0: |
| 2325 | # We haven't moved from the start point. |
| 2326 | return self._pack_cookie(start_pos, start_flags) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2327 | |
| 2328 | # Feed the decoder one byte at a time. As we go, note the |
| 2329 | # nearest "safe start point" before the current location |
| 2330 | # (a point where the decoder has nothing buffered, so seek() |
| 2331 | # can safely start from there and advance to this location). |
Antoine Pitrou | 211b81d | 2011-02-25 20:27:33 +0000 | [diff] [blame] | 2332 | bytes_fed = 0 |
| 2333 | need_eof = 0 |
| 2334 | # Chars decoded since `start_pos` |
| 2335 | chars_decoded = 0 |
| 2336 | for i in range(skip_bytes, len(next_input)): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2337 | bytes_fed += 1 |
Antoine Pitrou | 211b81d | 2011-02-25 20:27:33 +0000 | [diff] [blame] | 2338 | chars_decoded += len(decoder.decode(next_input[i:i+1])) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2339 | dec_buffer, dec_flags = decoder.getstate() |
| 2340 | if not dec_buffer and chars_decoded <= chars_to_skip: |
| 2341 | # Decoder buffer is empty, so this is a safe start point. |
| 2342 | start_pos += bytes_fed |
| 2343 | chars_to_skip -= chars_decoded |
| 2344 | start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0 |
| 2345 | if chars_decoded >= chars_to_skip: |
| 2346 | break |
| 2347 | else: |
| 2348 | # We didn't get enough decoded data; signal EOF to get more. |
| 2349 | chars_decoded += len(decoder.decode(b'', final=True)) |
| 2350 | need_eof = 1 |
| 2351 | if chars_decoded < chars_to_skip: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 2352 | raise OSError("can't reconstruct logical file position") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2353 | |
| 2354 | # The returned cookie corresponds to the last safe start point. |
| 2355 | return self._pack_cookie( |
| 2356 | start_pos, start_flags, bytes_fed, need_eof, chars_to_skip) |
| 2357 | finally: |
| 2358 | decoder.setstate(saved_state) |
| 2359 | |
| 2360 | def truncate(self, pos=None): |
| 2361 | self.flush() |
| 2362 | if pos is None: |
| 2363 | pos = self.tell() |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 2364 | return self.buffer.truncate(pos) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2365 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 2366 | def detach(self): |
| 2367 | if self.buffer is None: |
| 2368 | raise ValueError("buffer is already detached") |
| 2369 | self.flush() |
Antoine Pitrou | 7f8f418 | 2010-12-21 21:20:59 +0000 | [diff] [blame] | 2370 | buffer = self._buffer |
| 2371 | self._buffer = None |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 2372 | return buffer |
| 2373 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2374 | def seek(self, cookie, whence=0): |
Antoine Pitrou | 85e3ee7 | 2015-04-13 20:01:21 +0200 | [diff] [blame] | 2375 | def _reset_encoder(position): |
| 2376 | """Reset the encoder (merely useful for proper BOM handling)""" |
| 2377 | try: |
| 2378 | encoder = self._encoder or self._get_encoder() |
| 2379 | except LookupError: |
| 2380 | # Sometimes the encoder doesn't exist |
| 2381 | pass |
| 2382 | else: |
| 2383 | if position != 0: |
| 2384 | encoder.setstate(0) |
| 2385 | else: |
| 2386 | encoder.reset() |
| 2387 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2388 | if self.closed: |
| 2389 | raise ValueError("tell on closed file") |
| 2390 | if not self._seekable: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 2391 | raise UnsupportedOperation("underlying stream is not seekable") |
ngie-eign | 848037c | 2019-03-02 23:28:26 -0800 | [diff] [blame] | 2392 | if whence == SEEK_CUR: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2393 | if cookie != 0: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 2394 | raise UnsupportedOperation("can't do nonzero cur-relative seeks") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2395 | # Seeking to the current position should attempt to |
| 2396 | # sync the underlying buffer with the current position. |
| 2397 | whence = 0 |
| 2398 | cookie = self.tell() |
ngie-eign | 848037c | 2019-03-02 23:28:26 -0800 | [diff] [blame] | 2399 | elif whence == SEEK_END: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2400 | if cookie != 0: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 2401 | raise UnsupportedOperation("can't do nonzero end-relative seeks") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2402 | self.flush() |
ngie-eign | 848037c | 2019-03-02 23:28:26 -0800 | [diff] [blame] | 2403 | position = self.buffer.seek(0, whence) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2404 | self._set_decoded_chars('') |
| 2405 | self._snapshot = None |
| 2406 | if self._decoder: |
| 2407 | self._decoder.reset() |
Antoine Pitrou | 85e3ee7 | 2015-04-13 20:01:21 +0200 | [diff] [blame] | 2408 | _reset_encoder(position) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2409 | return position |
| 2410 | if whence != 0: |
Jesus Cea | 9436361 | 2012-06-22 18:32:07 +0200 | [diff] [blame] | 2411 | raise ValueError("unsupported whence (%r)" % (whence,)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2412 | if cookie < 0: |
| 2413 | raise ValueError("negative seek position %r" % (cookie,)) |
| 2414 | self.flush() |
| 2415 | |
| 2416 | # The strategy of seek() is to go back to the safe start point |
| 2417 | # and replay the effect of read(chars_to_skip) from there. |
| 2418 | start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \ |
| 2419 | self._unpack_cookie(cookie) |
| 2420 | |
| 2421 | # Seek back to the safe start point. |
| 2422 | self.buffer.seek(start_pos) |
| 2423 | self._set_decoded_chars('') |
| 2424 | self._snapshot = None |
| 2425 | |
| 2426 | # Restore the decoder to its state from the safe start point. |
Benjamin Peterson | 9363a65 | 2009-03-05 00:42:09 +0000 | [diff] [blame] | 2427 | if cookie == 0 and self._decoder: |
| 2428 | self._decoder.reset() |
| 2429 | elif self._decoder or dec_flags or chars_to_skip: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2430 | self._decoder = self._decoder or self._get_decoder() |
| 2431 | self._decoder.setstate((b'', dec_flags)) |
| 2432 | self._snapshot = (dec_flags, b'') |
| 2433 | |
| 2434 | if chars_to_skip: |
| 2435 | # Just like _read_chunk, feed the decoder and save a snapshot. |
| 2436 | input_chunk = self.buffer.read(bytes_to_feed) |
| 2437 | self._set_decoded_chars( |
| 2438 | self._decoder.decode(input_chunk, need_eof)) |
| 2439 | self._snapshot = (dec_flags, input_chunk) |
| 2440 | |
| 2441 | # Skip chars_to_skip of the decoded characters. |
| 2442 | if len(self._decoded_chars) < chars_to_skip: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 2443 | raise OSError("can't restore logical file position") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2444 | self._decoded_chars_used = chars_to_skip |
| 2445 | |
Antoine Pitrou | 85e3ee7 | 2015-04-13 20:01:21 +0200 | [diff] [blame] | 2446 | _reset_encoder(cookie) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2447 | return cookie |
| 2448 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2449 | def read(self, size=None): |
Benjamin Peterson | a1b4901 | 2009-03-31 23:11:32 +0000 | [diff] [blame] | 2450 | self._checkReadable() |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2451 | if size is None: |
| 2452 | size = -1 |
Oren Milman | de50360 | 2017-08-24 21:33:42 +0300 | [diff] [blame] | 2453 | else: |
| 2454 | try: |
| 2455 | size_index = size.__index__ |
| 2456 | except AttributeError: |
| 2457 | raise TypeError(f"{size!r} is not an integer") |
| 2458 | else: |
| 2459 | size = size_index() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2460 | decoder = self._decoder or self._get_decoder() |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2461 | if size < 0: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2462 | # Read everything. |
| 2463 | result = (self._get_decoded_chars() + |
| 2464 | decoder.decode(self.buffer.read(), final=True)) |
| 2465 | self._set_decoded_chars('') |
| 2466 | self._snapshot = None |
| 2467 | return result |
| 2468 | else: |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2469 | # Keep reading chunks until we have size characters to return. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2470 | eof = False |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2471 | result = self._get_decoded_chars(size) |
| 2472 | while len(result) < size and not eof: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2473 | eof = not self._read_chunk() |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2474 | result += self._get_decoded_chars(size - len(result)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2475 | return result |
| 2476 | |
| 2477 | def __next__(self): |
| 2478 | self._telling = False |
| 2479 | line = self.readline() |
| 2480 | if not line: |
| 2481 | self._snapshot = None |
| 2482 | self._telling = self._seekable |
| 2483 | raise StopIteration |
| 2484 | return line |
| 2485 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2486 | def readline(self, size=None): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2487 | if self.closed: |
| 2488 | raise ValueError("read from closed file") |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2489 | if size is None: |
| 2490 | size = -1 |
Oren Milman | de50360 | 2017-08-24 21:33:42 +0300 | [diff] [blame] | 2491 | else: |
| 2492 | try: |
| 2493 | size_index = size.__index__ |
| 2494 | except AttributeError: |
| 2495 | raise TypeError(f"{size!r} is not an integer") |
| 2496 | else: |
| 2497 | size = size_index() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2498 | |
| 2499 | # Grab all the decoded text (we will rewind any extra bits later). |
| 2500 | line = self._get_decoded_chars() |
| 2501 | |
| 2502 | start = 0 |
| 2503 | # Make the decoder if it doesn't already exist. |
| 2504 | if not self._decoder: |
| 2505 | self._get_decoder() |
| 2506 | |
| 2507 | pos = endpos = None |
| 2508 | while True: |
| 2509 | if self._readtranslate: |
| 2510 | # Newlines are already translated, only search for \n |
| 2511 | pos = line.find('\n', start) |
| 2512 | if pos >= 0: |
| 2513 | endpos = pos + 1 |
| 2514 | break |
| 2515 | else: |
| 2516 | start = len(line) |
| 2517 | |
| 2518 | elif self._readuniversal: |
| 2519 | # Universal newline search. Find any of \r, \r\n, \n |
| 2520 | # The decoder ensures that \r\n are not split in two pieces |
| 2521 | |
| 2522 | # In C we'd look for these in parallel of course. |
| 2523 | nlpos = line.find("\n", start) |
| 2524 | crpos = line.find("\r", start) |
| 2525 | if crpos == -1: |
| 2526 | if nlpos == -1: |
| 2527 | # Nothing found |
| 2528 | start = len(line) |
| 2529 | else: |
| 2530 | # Found \n |
| 2531 | endpos = nlpos + 1 |
| 2532 | break |
| 2533 | elif nlpos == -1: |
| 2534 | # Found lone \r |
| 2535 | endpos = crpos + 1 |
| 2536 | break |
| 2537 | elif nlpos < crpos: |
| 2538 | # Found \n |
| 2539 | endpos = nlpos + 1 |
| 2540 | break |
| 2541 | elif nlpos == crpos + 1: |
| 2542 | # Found \r\n |
| 2543 | endpos = crpos + 2 |
| 2544 | break |
| 2545 | else: |
| 2546 | # Found \r |
| 2547 | endpos = crpos + 1 |
| 2548 | break |
| 2549 | else: |
| 2550 | # non-universal |
| 2551 | pos = line.find(self._readnl) |
| 2552 | if pos >= 0: |
| 2553 | endpos = pos + len(self._readnl) |
| 2554 | break |
| 2555 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2556 | if size >= 0 and len(line) >= size: |
| 2557 | endpos = size # reached length size |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2558 | break |
| 2559 | |
| 2560 | # No line ending seen yet - get more data' |
| 2561 | while self._read_chunk(): |
| 2562 | if self._decoded_chars: |
| 2563 | break |
| 2564 | if self._decoded_chars: |
| 2565 | line += self._get_decoded_chars() |
| 2566 | else: |
| 2567 | # end of file |
| 2568 | self._set_decoded_chars('') |
| 2569 | self._snapshot = None |
| 2570 | return line |
| 2571 | |
Serhiy Storchaka | 3c41154 | 2013-09-16 23:18:10 +0300 | [diff] [blame] | 2572 | if size >= 0 and endpos > size: |
| 2573 | endpos = size # don't exceed size |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2574 | |
| 2575 | # Rewind _decoded_chars to just after the line ending we found. |
| 2576 | self._rewind_decoded_chars(len(line) - endpos) |
| 2577 | return line[:endpos] |
| 2578 | |
| 2579 | @property |
| 2580 | def newlines(self): |
| 2581 | return self._decoder.newlines if self._decoder else None |
| 2582 | |
| 2583 | |
| 2584 | class StringIO(TextIOWrapper): |
| 2585 | """Text I/O implementation using an in-memory buffer. |
| 2586 | |
| 2587 | The initial_value argument sets the value of object. The newline |
| 2588 | argument is like the one of TextIOWrapper's constructor. |
| 2589 | """ |
| 2590 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2591 | def __init__(self, initial_value="", newline="\n"): |
| 2592 | super(StringIO, self).__init__(BytesIO(), |
| 2593 | encoding="utf-8", |
Serhiy Storchaka | c92ea76 | 2014-01-29 11:33:26 +0200 | [diff] [blame] | 2594 | errors="surrogatepass", |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2595 | newline=newline) |
Antoine Pitrou | 1144648 | 2009-04-04 14:09:30 +0000 | [diff] [blame] | 2596 | # Issue #5645: make universal newlines semantics the same as in the |
| 2597 | # C version, even under Windows. |
| 2598 | if newline is None: |
| 2599 | self._writetranslate = False |
Alexandre Vassalotti | d2bb18b | 2009-07-22 03:07:33 +0000 | [diff] [blame] | 2600 | if initial_value is not None: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2601 | if not isinstance(initial_value, str): |
Alexandre Vassalotti | d2bb18b | 2009-07-22 03:07:33 +0000 | [diff] [blame] | 2602 | raise TypeError("initial_value must be str or None, not {0}" |
| 2603 | .format(type(initial_value).__name__)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2604 | self.write(initial_value) |
| 2605 | self.seek(0) |
| 2606 | |
| 2607 | def getvalue(self): |
| 2608 | self.flush() |
Antoine Pitrou | 57839a6 | 2014-02-02 23:37:29 +0100 | [diff] [blame] | 2609 | decoder = self._decoder or self._get_decoder() |
| 2610 | old_state = decoder.getstate() |
| 2611 | decoder.reset() |
| 2612 | try: |
| 2613 | return decoder.decode(self.buffer.getvalue(), final=True) |
| 2614 | finally: |
| 2615 | decoder.setstate(old_state) |
Benjamin Peterson | 9fd459a | 2009-03-09 00:09:44 +0000 | [diff] [blame] | 2616 | |
| 2617 | def __repr__(self): |
| 2618 | # TextIOWrapper tells the encoding in its repr. In StringIO, |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 2619 | # that's an implementation detail. |
Benjamin Peterson | 9fd459a | 2009-03-09 00:09:44 +0000 | [diff] [blame] | 2620 | return object.__repr__(self) |
Benjamin Peterson | b487e63 | 2009-03-21 03:08:31 +0000 | [diff] [blame] | 2621 | |
| 2622 | @property |
Benjamin Peterson | 0926ad1 | 2009-06-06 18:02:12 +0000 | [diff] [blame] | 2623 | def errors(self): |
| 2624 | return None |
| 2625 | |
| 2626 | @property |
Benjamin Peterson | b487e63 | 2009-03-21 03:08:31 +0000 | [diff] [blame] | 2627 | def encoding(self): |
| 2628 | return None |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 2629 | |
| 2630 | def detach(self): |
| 2631 | # This doesn't make sense on StringIO. |
| 2632 | self._unsupported("detach") |