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