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