Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 1 | """New I/O library conforming to PEP 3116. |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 3 | This is an early prototype; eventually some of this will be |
| 4 | reimplemented in C and the rest may be turned into a package. |
| 5 | |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 6 | Conformance of alternative implementations: all arguments are intended |
| 7 | to be positional-only except the arguments of the open() function. |
| 8 | Argument names except those of the open() function are not part of the |
| 9 | specification. Instance variables and methods whose name starts with |
| 10 | a leading underscore are not part of the specification (except "magic" |
| 11 | names like __iter__). Only the top-level names listed in the __all__ |
| 12 | variable are part of the specification. |
Guido van Rossum | c819dea | 2007-03-15 18:59:31 +0000 | [diff] [blame] | 13 | |
| 14 | XXX need to default buffer size to 1 if isatty() |
| 15 | XXX need to support 1 meaning line-buffered |
| 16 | XXX change behavior of blocking I/O |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 17 | XXX don't use assert to validate input requirements |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 18 | """ |
| 19 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 20 | __author__ = ("Guido van Rossum <guido@python.org>, " |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 21 | "Mike Verdone <mike.verdone@gmail.com>, " |
| 22 | "Mark Russell <mark.russell@zen.co.uk>") |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 23 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 24 | __all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO", |
| 25 | "SocketIO", "BytesIO", "StringIO", "BufferedIOBase", |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 26 | "BufferedReader", "BufferedWriter", "BufferedRWPair", |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 27 | "BufferedRandom", "TextIOBase", "TextIOWrapper"] |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 28 | |
| 29 | import os |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 30 | import sys |
| 31 | import codecs |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 32 | import _fileio |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 33 | import warnings |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 34 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 35 | DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 36 | |
| 37 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 38 | class BlockingIOError(IOError): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 39 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 40 | """Exception raised when I/O would block on a non-blocking I/O stream.""" |
| 41 | |
| 42 | def __init__(self, errno, strerror, characters_written=0): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 43 | IOError.__init__(self, errno, strerror) |
| 44 | self.characters_written = characters_written |
| 45 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 46 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 47 | def open(file, mode="r", buffering=None, *, encoding=None): |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 48 | """Replacement for the built-in open function. |
| 49 | |
| 50 | Args: |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 51 | file: string giving the name of the file to be opened; |
| 52 | or integer file descriptor of the file to be wrapped (*) |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 53 | mode: optional mode string; see below |
| 54 | buffering: optional int >= 0 giving the buffer size; values |
| 55 | can be: 0 = unbuffered, 1 = line buffered, |
| 56 | larger = fully buffered |
| 57 | encoding: optional string giving the text encoding (*must* be given |
| 58 | as a keyword argument) |
| 59 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 60 | (*) If a file descriptor is given, it is closed when the returned |
| 61 | I/O object is closed. If you don't want this to happen, use |
| 62 | os.dup() to create a duplicate file descriptor. |
| 63 | |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 64 | Mode strings characters: |
| 65 | 'r': open for reading (default) |
| 66 | 'w': open for writing, truncating the file first |
| 67 | 'a': open for writing, appending to the end if the file exists |
| 68 | 'b': binary mode |
| 69 | 't': text mode (default) |
| 70 | '+': open a disk file for updating (implies reading and writing) |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 71 | 'U': universal newline mode (for backwards compatibility) |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 72 | |
| 73 | Constraints: |
| 74 | - encoding must not be given when a binary mode is given |
| 75 | - buffering must not be zero when a text mode is given |
| 76 | |
| 77 | Returns: |
| 78 | Depending on the mode and buffering arguments, either a raw |
| 79 | binary stream, a buffered binary stream, or a buffered text |
| 80 | stream, open for reading and/or writing. |
| 81 | """ |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 82 | assert isinstance(file, (basestring, int)), repr(file) |
| 83 | assert isinstance(mode, basestring), repr(mode) |
| 84 | assert buffering is None or isinstance(buffering, int), repr(buffering) |
| 85 | assert encoding is None or isinstance(encoding, basestring), repr(encoding) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 86 | modes = set(mode) |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 87 | if modes - set("arwb+tU") or len(mode) > len(modes): |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 88 | raise ValueError("invalid mode: %r" % mode) |
| 89 | reading = "r" in modes |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 90 | writing = "w" in modes |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 91 | appending = "a" in modes |
| 92 | updating = "+" in modes |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 93 | text = "t" in modes |
| 94 | binary = "b" in modes |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 95 | if "U" in modes and not (reading or writing or appending): |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 96 | reading = True |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 97 | if text and binary: |
| 98 | raise ValueError("can't have text and binary mode at once") |
| 99 | if reading + writing + appending > 1: |
| 100 | raise ValueError("can't have read/write/append mode at once") |
| 101 | if not (reading or writing or appending): |
| 102 | raise ValueError("must have exactly one of read/write/append mode") |
| 103 | if binary and encoding is not None: |
| 104 | raise ValueError("binary mode doesn't take an encoding") |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 105 | raw = FileIO(file, |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 106 | (reading and "r" or "") + |
| 107 | (writing and "w" or "") + |
| 108 | (appending and "a" or "") + |
| 109 | (updating and "+" or "")) |
| 110 | if buffering is None: |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 111 | buffering = DEFAULT_BUFFER_SIZE |
| 112 | # XXX Should default to line buffering if os.isatty(raw.fileno()) |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 113 | try: |
| 114 | bs = os.fstat(raw.fileno()).st_blksize |
| 115 | except (os.error, AttributeError): |
Guido van Rossum | bb09b21 | 2007-03-18 03:36:28 +0000 | [diff] [blame] | 116 | pass |
| 117 | else: |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 118 | if bs > 1: |
| 119 | buffering = bs |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 120 | if buffering < 0: |
| 121 | raise ValueError("invalid buffering size") |
| 122 | if buffering == 0: |
| 123 | if binary: |
| 124 | return raw |
| 125 | raise ValueError("can't have unbuffered text I/O") |
| 126 | if updating: |
| 127 | buffer = BufferedRandom(raw, buffering) |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 128 | elif writing or appending: |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 129 | buffer = BufferedWriter(raw, buffering) |
| 130 | else: |
| 131 | assert reading |
| 132 | buffer = BufferedReader(raw, buffering) |
| 133 | if binary: |
| 134 | return buffer |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 135 | # XXX What about newline conventions? |
| 136 | textio = TextIOWrapper(buffer, encoding) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 137 | return textio |
| 138 | |
| 139 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 140 | class IOBase: |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 141 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 142 | """Base class for all I/O classes. |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 143 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 144 | This class provides dummy implementations for many methods that |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 145 | derived classes can override selectively; the default |
| 146 | implementations represent a file that cannot be read, written or |
| 147 | seeked. |
| 148 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 149 | This does not define read(), readinto() and write(), nor |
| 150 | readline() and friends, since their signatures vary per layer. |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 151 | |
| 152 | Not that calling any method (even inquiries) on a closed file is |
| 153 | undefined. Implementations may raise IOError in this case. |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 154 | """ |
| 155 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 156 | ### Internal ### |
| 157 | |
| 158 | def _unsupported(self, name: str) -> IOError: |
| 159 | """Internal: raise an exception for unsupported operations.""" |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 160 | raise IOError("%s.%s() not supported" % (self.__class__.__name__, |
| 161 | name)) |
| 162 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 163 | ### Positioning ### |
| 164 | |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 165 | def seek(self, pos: int, whence: int = 0) -> int: |
| 166 | """seek(pos: int, whence: int = 0) -> int. Change stream position. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 167 | |
| 168 | Seek to byte offset pos relative to position indicated by whence: |
| 169 | 0 Start of stream (the default). pos should be >= 0; |
| 170 | 1 Current position - whence may be negative; |
| 171 | 2 End of stream - whence usually negative. |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 172 | Returns the new absolute position. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 173 | """ |
| 174 | self._unsupported("seek") |
| 175 | |
| 176 | def tell(self) -> int: |
| 177 | """tell() -> int. Return current stream position.""" |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 178 | return self.seek(0, 1) |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 179 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame^] | 180 | def truncate(self, pos: int = None) -> int: |
| 181 | """truncate(size: int = None) -> int. Truncate file to size bytes. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 182 | |
| 183 | Size defaults to the current IO position as reported by tell(). |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame^] | 184 | Returns the new size. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 185 | """ |
| 186 | self._unsupported("truncate") |
| 187 | |
| 188 | ### Flush and close ### |
| 189 | |
| 190 | def flush(self) -> None: |
| 191 | """flush() -> None. Flushes write buffers, if applicable. |
| 192 | |
| 193 | This is a no-op for read-only and non-blocking streams. |
| 194 | """ |
| 195 | |
| 196 | __closed = False |
| 197 | |
| 198 | def close(self) -> None: |
| 199 | """close() -> None. Flushes and closes the IO object. |
| 200 | |
| 201 | This must be idempotent. It should also set a flag for the |
| 202 | 'closed' property (see below) to test. |
| 203 | """ |
| 204 | if not self.__closed: |
| 205 | self.__closed = True |
| 206 | self.flush() |
| 207 | |
| 208 | def __del__(self) -> None: |
| 209 | """Destructor. Calls close().""" |
| 210 | # The try/except block is in case this is called at program |
| 211 | # exit time, when it's possible that globals have already been |
| 212 | # deleted, and then the close() call might fail. Since |
| 213 | # there's nothing we can do about such failures and they annoy |
| 214 | # the end users, we suppress the traceback. |
| 215 | try: |
| 216 | self.close() |
| 217 | except: |
| 218 | pass |
| 219 | |
| 220 | ### Inquiries ### |
| 221 | |
| 222 | def seekable(self) -> bool: |
| 223 | """seekable() -> bool. Return whether object supports random access. |
| 224 | |
| 225 | If False, seek(), tell() and truncate() will raise IOError. |
| 226 | This method may need to do a test seek(). |
| 227 | """ |
| 228 | return False |
| 229 | |
| 230 | def readable(self) -> bool: |
| 231 | """readable() -> bool. Return whether object was opened for reading. |
| 232 | |
| 233 | If False, read() will raise IOError. |
| 234 | """ |
| 235 | return False |
| 236 | |
| 237 | def writable(self) -> bool: |
| 238 | """writable() -> bool. Return whether object was opened for writing. |
| 239 | |
| 240 | If False, write() and truncate() will raise IOError. |
| 241 | """ |
| 242 | return False |
| 243 | |
| 244 | @property |
| 245 | def closed(self): |
| 246 | """closed: bool. True iff the file has been closed. |
| 247 | |
| 248 | For backwards compatibility, this is a property, not a predicate. |
| 249 | """ |
| 250 | return self.__closed |
| 251 | |
| 252 | ### Context manager ### |
| 253 | |
| 254 | def __enter__(self) -> "IOBase": # That's a forward reference |
| 255 | """Context management protocol. Returns self.""" |
| 256 | return self |
| 257 | |
| 258 | def __exit__(self, *args) -> None: |
| 259 | """Context management protocol. Calls close()""" |
| 260 | self.close() |
| 261 | |
| 262 | ### Lower-level APIs ### |
| 263 | |
| 264 | # XXX Should these be present even if unimplemented? |
| 265 | |
| 266 | def fileno(self) -> int: |
| 267 | """fileno() -> int. Returns underlying file descriptor if one exists. |
| 268 | |
| 269 | Raises IOError if the IO object does not use a file descriptor. |
| 270 | """ |
| 271 | self._unsupported("fileno") |
| 272 | |
| 273 | def isatty(self) -> bool: |
| 274 | """isatty() -> int. Returns whether this is an 'interactive' stream. |
| 275 | |
| 276 | Returns False if we don't know. |
| 277 | """ |
| 278 | return False |
| 279 | |
| 280 | |
| 281 | class RawIOBase(IOBase): |
| 282 | |
| 283 | """Base class for raw binary I/O. |
| 284 | |
| 285 | The read() method is implemented by calling readinto(); derived |
| 286 | classes that want to support read() only need to implement |
| 287 | readinto() as a primitive operation. In general, readinto() |
| 288 | can be more efficient than read(). |
| 289 | |
| 290 | (It would be tempting to also provide an implementation of |
| 291 | readinto() in terms of read(), in case the latter is a more |
| 292 | suitable primitive operation, but that would lead to nasty |
| 293 | recursion in case a subclass doesn't implement either.) |
| 294 | """ |
| 295 | |
| 296 | def read(self, n: int) -> bytes: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 297 | """read(n: int) -> bytes. Read and return up to n bytes. |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 298 | |
| 299 | Returns an empty bytes array on EOF, or None if the object is |
| 300 | set not to block and has no data to read. |
| 301 | """ |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 302 | b = bytes(n.__index__()) |
Guido van Rossum | 00efead | 2007-03-07 05:23:25 +0000 | [diff] [blame] | 303 | n = self.readinto(b) |
| 304 | del b[n:] |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 305 | return b |
| 306 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 307 | def readinto(self, b: bytes) -> int: |
| 308 | """readinto(b: bytes) -> int. Read up to len(b) bytes into b. |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 309 | |
| 310 | Returns number of bytes read (0 for EOF), or None if the object |
| 311 | is set not to block as has no data to read. |
| 312 | """ |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 313 | self._unsupported("readinto") |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 314 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 315 | def write(self, b: bytes) -> int: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 316 | """write(b: bytes) -> int. Write the given buffer to the IO stream. |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 317 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 318 | 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] | 319 | """ |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 320 | self._unsupported("write") |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 321 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 322 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 323 | class FileIO(_fileio._FileIO, RawIOBase): |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 324 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 325 | """Raw I/O implementation for OS files. |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 326 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 327 | This multiply inherits from _FileIO and RawIOBase to make |
| 328 | isinstance(io.FileIO(), io.RawIOBase) return True without |
| 329 | requiring that _fileio._FileIO inherits from io.RawIOBase (which |
| 330 | would be hard to do since _fileio.c is written in C). |
| 331 | """ |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 332 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame^] | 333 | def close(self): |
| 334 | _fileio._FileIO.close(self) |
| 335 | RawIOBase.close(self) |
| 336 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 337 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 338 | class SocketIO(RawIOBase): |
| 339 | |
| 340 | """Raw I/O implementation for stream sockets.""" |
| 341 | |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 342 | # XXX More docs |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 343 | # XXX Hook this up to socket.py |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 344 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 345 | def __init__(self, sock, mode): |
| 346 | assert mode in ("r", "w", "rw") |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 347 | RawIOBase.__init__(self) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 348 | self._sock = sock |
| 349 | self._mode = mode |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 350 | |
| 351 | def readinto(self, b): |
| 352 | return self._sock.recv_into(b) |
| 353 | |
| 354 | def write(self, b): |
| 355 | return self._sock.send(b) |
| 356 | |
| 357 | def close(self): |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 358 | if not self.closed: |
| 359 | RawIOBase.close() |
| 360 | self._sock.close() |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 361 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 362 | def readable(self): |
| 363 | return "r" in self._mode |
| 364 | |
| 365 | def writable(self): |
| 366 | return "w" in self._mode |
| 367 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 368 | def fileno(self): |
| 369 | return self._sock.fileno() |
Neal Norwitz | 8b41c3d | 2007-02-27 06:26:14 +0000 | [diff] [blame] | 370 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 371 | |
Guido van Rossum | cce92b2 | 2007-04-10 14:41:39 +0000 | [diff] [blame] | 372 | class BufferedIOBase(IOBase): |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 373 | |
| 374 | """Base class for buffered IO objects. |
| 375 | |
| 376 | The main difference with RawIOBase is that the read() method |
| 377 | supports omitting the size argument, and does not have a default |
| 378 | implementation that defers to readinto(). |
| 379 | |
| 380 | In addition, read(), readinto() and write() may raise |
| 381 | BlockingIOError if the underlying raw stream is in non-blocking |
| 382 | mode and not ready; unlike their raw counterparts, they will never |
| 383 | return None. |
| 384 | |
| 385 | A typical implementation should not inherit from a RawIOBase |
| 386 | implementation, but wrap one. |
| 387 | """ |
| 388 | |
| 389 | def read(self, n: int = -1) -> bytes: |
| 390 | """read(n: int = -1) -> bytes. Read and return up to n bytes. |
| 391 | |
| 392 | If the argument is omitted, or negative, reads and returns all |
| 393 | data until EOF. |
| 394 | |
| 395 | If the argument is positive, and the underlying raw stream is |
| 396 | not 'interactive', multiple raw reads may be issued to satisfy |
| 397 | the byte count (unless EOF is reached first). But for |
| 398 | interactive raw streams (XXX and for pipes?), at most one raw |
| 399 | read will be issued, and a short result does not imply that |
| 400 | EOF is imminent. |
| 401 | |
| 402 | Returns an empty bytes array on EOF. |
| 403 | |
| 404 | Raises BlockingIOError if the underlying raw stream has no |
| 405 | data at the moment. |
| 406 | """ |
| 407 | self._unsupported("read") |
| 408 | |
| 409 | def readinto(self, b: bytes) -> int: |
| 410 | """readinto(b: bytes) -> int. Read up to len(b) bytes into b. |
| 411 | |
| 412 | Like read(), this may issue multiple reads to the underlying |
| 413 | raw stream, unless the latter is 'interactive' (XXX or a |
| 414 | pipe?). |
| 415 | |
| 416 | Returns the number of bytes read (0 for EOF). |
| 417 | |
| 418 | Raises BlockingIOError if the underlying raw stream has no |
| 419 | data at the moment. |
| 420 | """ |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame^] | 421 | data = self.read(len(b)) |
| 422 | n = len(data) |
| 423 | b[:n] = data |
| 424 | return n |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 425 | |
| 426 | def write(self, b: bytes) -> int: |
| 427 | """write(b: bytes) -> int. Write the given buffer to the IO stream. |
| 428 | |
| 429 | Returns the number of bytes written, which is never less than |
| 430 | len(b). |
| 431 | |
| 432 | Raises BlockingIOError if the buffer is full and the |
| 433 | underlying raw stream cannot accept more data at the moment. |
| 434 | """ |
| 435 | self._unsupported("write") |
| 436 | |
| 437 | |
| 438 | class _BufferedIOMixin(BufferedIOBase): |
| 439 | |
| 440 | """A mixin implementation of BufferedIOBase with an underlying raw stream. |
| 441 | |
| 442 | This passes most requests on to the underlying raw stream. It |
| 443 | does *not* provide implementations of read(), readinto() or |
| 444 | write(). |
| 445 | """ |
| 446 | |
| 447 | def __init__(self, raw): |
| 448 | self.raw = raw |
| 449 | |
| 450 | ### Positioning ### |
| 451 | |
| 452 | def seek(self, pos, whence=0): |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 453 | return self.raw.seek(pos, whence) |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 454 | |
| 455 | def tell(self): |
| 456 | return self.raw.tell() |
| 457 | |
| 458 | def truncate(self, pos=None): |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame^] | 459 | return self.raw.truncate(pos) |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 460 | |
| 461 | ### Flush and close ### |
| 462 | |
| 463 | def flush(self): |
| 464 | self.raw.flush() |
| 465 | |
| 466 | def close(self): |
| 467 | self.flush() |
| 468 | self.raw.close() |
| 469 | |
| 470 | ### Inquiries ### |
| 471 | |
| 472 | def seekable(self): |
| 473 | return self.raw.seekable() |
| 474 | |
| 475 | def readable(self): |
| 476 | return self.raw.readable() |
| 477 | |
| 478 | def writable(self): |
| 479 | return self.raw.writable() |
| 480 | |
| 481 | @property |
| 482 | def closed(self): |
| 483 | return self.raw.closed |
| 484 | |
| 485 | ### Lower-level APIs ### |
| 486 | |
| 487 | def fileno(self): |
| 488 | return self.raw.fileno() |
| 489 | |
| 490 | def isatty(self): |
| 491 | return self.raw.isatty() |
| 492 | |
| 493 | |
| 494 | class _MemoryIOMixin(BufferedIOBase): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 495 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 496 | # XXX docstring |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 497 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 498 | def __init__(self, buffer): |
| 499 | self._buffer = buffer |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 500 | self._pos = 0 |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 501 | |
| 502 | def getvalue(self): |
| 503 | return self._buffer |
| 504 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 505 | def read(self, n=-1): |
| 506 | assert n is not None |
| 507 | if n < 0: |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 508 | n = len(self._buffer) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 509 | newpos = min(len(self._buffer), self._pos + n) |
| 510 | b = self._buffer[self._pos : newpos] |
| 511 | self._pos = newpos |
| 512 | return b |
| 513 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 514 | def write(self, b): |
| 515 | n = len(b) |
| 516 | newpos = self._pos + n |
| 517 | self._buffer[self._pos:newpos] = b |
| 518 | self._pos = newpos |
| 519 | return n |
| 520 | |
| 521 | def seek(self, pos, whence=0): |
| 522 | if whence == 0: |
| 523 | self._pos = max(0, pos) |
| 524 | elif whence == 1: |
| 525 | self._pos = max(0, self._pos + pos) |
| 526 | elif whence == 2: |
| 527 | self._pos = max(0, len(self._buffer) + pos) |
| 528 | else: |
| 529 | raise IOError("invalid whence value") |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 530 | return self._pos |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 531 | |
| 532 | def tell(self): |
| 533 | return self._pos |
| 534 | |
| 535 | def truncate(self, pos=None): |
| 536 | if pos is None: |
| 537 | pos = self._pos |
| 538 | else: |
| 539 | self._pos = max(0, pos) |
| 540 | del self._buffer[pos:] |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame^] | 541 | return pos |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 542 | |
| 543 | def readable(self): |
| 544 | return True |
| 545 | |
| 546 | def writable(self): |
| 547 | return True |
| 548 | |
| 549 | def seekable(self): |
| 550 | return True |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 551 | |
| 552 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 553 | class BytesIO(_MemoryIOMixin): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 554 | |
| 555 | """Buffered I/O implementation using a bytes buffer, like StringIO.""" |
| 556 | |
| 557 | # XXX More docs |
| 558 | |
| 559 | def __init__(self, inital_bytes=None): |
| 560 | buffer = b"" |
| 561 | if inital_bytes is not None: |
| 562 | buffer += inital_bytes |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 563 | _MemoryIOMixin.__init__(self, buffer) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 564 | |
| 565 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 566 | # XXX This should inherit from TextIOBase |
| 567 | class StringIO(_MemoryIOMixin): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 568 | |
| 569 | """Buffered I/O implementation using a string buffer, like StringIO.""" |
| 570 | |
| 571 | # XXX More docs |
| 572 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 573 | # Reuses the same code as BytesIO, just with a string rather that |
| 574 | # bytes as the _buffer value. |
| 575 | |
| 576 | # XXX This doesn't work; _MemoryIOMixin's write() and truncate() |
| 577 | # methods assume the buffer is mutable. Simply redefining those |
| 578 | # to use slice concatenation will make it awfully slow (in fact, |
| 579 | # quadratic in the number of write() calls). |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 580 | |
| 581 | def __init__(self, inital_string=None): |
| 582 | buffer = "" |
| 583 | if inital_string is not None: |
| 584 | buffer += inital_string |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 585 | _MemoryIOMixin.__init__(self, buffer) |
| 586 | |
| 587 | def readinto(self, b: bytes) -> int: |
| 588 | self._unsupported("readinto") |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 589 | |
| 590 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 591 | class BufferedReader(_BufferedIOMixin): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 592 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 593 | """Buffer for a readable sequential RawIO object.""" |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 594 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 595 | def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 596 | """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] | 597 | """ |
| 598 | assert raw.readable() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 599 | _BufferedIOMixin.__init__(self, raw) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 600 | self._read_buf = b"" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 601 | self.buffer_size = buffer_size |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 602 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 603 | def read(self, n=-1): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 604 | """Read n bytes. |
| 605 | |
| 606 | Returns exactly n bytes of data unless the underlying raw IO |
| 607 | stream reaches EOF of if the call would block in non-blocking |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 608 | 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] | 609 | block. |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 610 | """ |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 611 | assert n is not None |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 612 | nodata_val = b"" |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 613 | while n < 0 or len(self._read_buf) < n: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 614 | to_read = max(self.buffer_size, |
| 615 | n if n is not None else 2*len(self._read_buf)) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 616 | current = self.raw.read(to_read) |
| 617 | |
| 618 | if current in (b"", None): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 619 | nodata_val = current |
| 620 | break |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 621 | self._read_buf += current |
| 622 | if self._read_buf: |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 623 | if n < 0: |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 624 | n = len(self._read_buf) |
| 625 | out = self._read_buf[:n] |
| 626 | self._read_buf = self._read_buf[n:] |
| 627 | else: |
| 628 | out = nodata_val |
| 629 | return out |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 630 | |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 631 | def tell(self): |
| 632 | return self.raw.tell() - len(self._read_buf) |
| 633 | |
| 634 | def seek(self, pos, whence=0): |
| 635 | if whence == 1: |
| 636 | pos -= len(self._read_buf) |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 637 | pos = self.raw.seek(pos, whence) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 638 | self._read_buf = b"" |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 639 | return pos |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 640 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 641 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 642 | class BufferedWriter(_BufferedIOMixin): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 643 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 644 | # XXX docstring |
| 645 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 646 | def __init__(self, raw, |
| 647 | buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 648 | assert raw.writable() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 649 | _BufferedIOMixin.__init__(self, raw) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 650 | self.buffer_size = buffer_size |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 651 | self.max_buffer_size = (2*buffer_size |
| 652 | if max_buffer_size is None |
| 653 | else max_buffer_size) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 654 | self._write_buf = b"" |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 655 | |
| 656 | def write(self, b): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 657 | # XXX we can implement some more tricks to try and avoid partial writes |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 658 | if len(self._write_buf) > self.buffer_size: |
| 659 | # We're full, so let's pre-flush the buffer |
| 660 | try: |
| 661 | self.flush() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 662 | except BlockingIOError as e: |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 663 | # We can't accept anything else. |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 664 | # XXX Why not just let the exception pass through? |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 665 | raise BlockingIOError(e.errno, e.strerror, 0) |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 666 | self._write_buf.extend(b) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 667 | if len(self._write_buf) > self.buffer_size: |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 668 | try: |
| 669 | self.flush() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 670 | except BlockingIOError as e: |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 671 | if (len(self._write_buf) > self.max_buffer_size): |
| 672 | # We've hit max_buffer_size. We have to accept a partial |
| 673 | # write and cut back our buffer. |
| 674 | overage = len(self._write_buf) - self.max_buffer_size |
| 675 | self._write_buf = self._write_buf[:self.max_buffer_size] |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 676 | raise BlockingIOError(e.errno, e.strerror, overage) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame^] | 677 | return len(b) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 678 | |
| 679 | def flush(self): |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 680 | written = 0 |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 681 | try: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 682 | while self._write_buf: |
| 683 | n = self.raw.write(self._write_buf) |
| 684 | del self._write_buf[:n] |
| 685 | written += n |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 686 | except BlockingIOError as e: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 687 | n = e.characters_written |
| 688 | del self._write_buf[:n] |
| 689 | written += n |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 690 | raise BlockingIOError(e.errno, e.strerror, written) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 691 | |
| 692 | def tell(self): |
| 693 | return self.raw.tell() + len(self._write_buf) |
| 694 | |
| 695 | def seek(self, pos, whence=0): |
| 696 | self.flush() |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 697 | return self.raw.seek(pos, whence) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 698 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 699 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 700 | class BufferedRWPair(BufferedIOBase): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 701 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 702 | """A buffered reader and writer object together. |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 703 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 704 | A buffered reader object and buffered writer object put together |
| 705 | to form a sequential IO object that can read and write. |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 706 | |
| 707 | This is typically used with a socket or two-way pipe. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 708 | |
| 709 | XXX The usefulness of this (compared to having two separate IO |
| 710 | objects) is questionable. |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 711 | """ |
| 712 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 713 | def __init__(self, reader, writer, |
| 714 | buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): |
| 715 | """Constructor. |
| 716 | |
| 717 | The arguments are two RawIO instances. |
| 718 | """ |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 719 | assert reader.readable() |
| 720 | assert writer.writable() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 721 | self.reader = BufferedReader(reader, buffer_size) |
| 722 | self.writer = BufferedWriter(writer, buffer_size, max_buffer_size) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 723 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 724 | def read(self, n=-1): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 725 | return self.reader.read(n) |
| 726 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 727 | def readinto(self, b): |
| 728 | return self.reader.readinto(b) |
| 729 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 730 | def write(self, b): |
| 731 | return self.writer.write(b) |
| 732 | |
| 733 | def readable(self): |
| 734 | return self.reader.readable() |
| 735 | |
| 736 | def writable(self): |
| 737 | return self.writer.writable() |
| 738 | |
| 739 | def flush(self): |
| 740 | return self.writer.flush() |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 741 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 742 | def close(self): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 743 | self.writer.close() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 744 | self.reader.close() |
| 745 | |
| 746 | def isatty(self): |
| 747 | return self.reader.isatty() or self.writer.isatty() |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 748 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 749 | @property |
| 750 | def closed(self): |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 751 | return self.writer.closed() |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 752 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 753 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 754 | class BufferedRandom(BufferedWriter, BufferedReader): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 755 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 756 | # XXX docstring |
| 757 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 758 | def __init__(self, raw, |
| 759 | buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 760 | assert raw.seekable() |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 761 | BufferedReader.__init__(self, raw, buffer_size) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 762 | BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size) |
| 763 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 764 | def seek(self, pos, whence=0): |
| 765 | self.flush() |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 766 | # First do the raw seek, then empty the read buffer, so that |
| 767 | # 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] | 768 | pos = self.raw.seek(pos, whence) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 769 | self._read_buf = b"" |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 770 | return pos |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 771 | |
| 772 | def tell(self): |
| 773 | if (self._write_buf): |
| 774 | return self.raw.tell() + len(self._write_buf) |
| 775 | else: |
| 776 | return self.raw.tell() - len(self._read_buf) |
| 777 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 778 | def read(self, n=-1): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 779 | self.flush() |
| 780 | return BufferedReader.read(self, n) |
| 781 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 782 | def readinto(self, b): |
| 783 | self.flush() |
| 784 | return BufferedReader.readinto(self, b) |
| 785 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 786 | def write(self, b): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 787 | if self._read_buf: |
| 788 | self.raw.seek(-len(self._read_buf), 1) # Undo readahead |
| 789 | self._read_buf = b"" |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 790 | return BufferedWriter.write(self, b) |
| 791 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 792 | |
Guido van Rossum | cce92b2 | 2007-04-10 14:41:39 +0000 | [diff] [blame] | 793 | class TextIOBase(IOBase): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 794 | |
| 795 | """Base class for text I/O. |
| 796 | |
| 797 | This class provides a character and line based interface to stream I/O. |
| 798 | """ |
| 799 | |
| 800 | def read(self, n: int = -1) -> str: |
| 801 | """read(n: int = -1) -> str. Read at most n characters from stream. |
| 802 | |
| 803 | Read from underlying buffer until we have n characters or we hit EOF. |
| 804 | If n is negative or omitted, read until EOF. |
| 805 | """ |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 806 | self._unsupported("read") |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 807 | |
| 808 | def write(self, s: str): |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 809 | """write(s: str) -> None. Write string s to stream.""" |
| 810 | self._unsupported("write") |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 811 | |
| 812 | def readline(self) -> str: |
| 813 | """readline() -> str. Read until newline or EOF. |
| 814 | |
| 815 | Returns an empty string if EOF is hit immediately. |
| 816 | """ |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 817 | self._unsupported("readline") |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 818 | |
| 819 | def __iter__(self): |
| 820 | """__iter__() -> Iterator. Return line iterator (actually just self). |
| 821 | """ |
| 822 | return self |
| 823 | |
| 824 | def next(self): |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 825 | """Same as readline() except raises StopIteration on immediate EOF.""" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 826 | line = self.readline() |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 827 | if not line: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 828 | raise StopIteration |
| 829 | return line |
| 830 | |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 831 | # The following are provided for backwards compatibility |
| 832 | |
| 833 | def readlines(self, hint=None): |
| 834 | if hint is None: |
| 835 | return list(self) |
| 836 | n = 0 |
| 837 | lines = [] |
| 838 | while not lines or n < hint: |
| 839 | line = self.readline() |
| 840 | if not line: |
| 841 | break |
| 842 | lines.append(line) |
| 843 | n += len(line) |
| 844 | return lines |
| 845 | |
| 846 | def writelines(self, lines): |
| 847 | for line in lines: |
| 848 | self.write(line) |
| 849 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 850 | |
| 851 | class TextIOWrapper(TextIOBase): |
| 852 | |
| 853 | """Buffered text stream. |
| 854 | |
| 855 | Character and line based layer over a BufferedIOBase object. |
| 856 | """ |
| 857 | |
| 858 | # XXX tell(), seek() |
| 859 | |
| 860 | def __init__(self, buffer, encoding=None, newline=None): |
| 861 | if newline not in (None, '\n', '\r\n'): |
| 862 | raise IOError("illegal newline %s" % newline) # XXX: ValueError? |
| 863 | if encoding is None: |
| 864 | # XXX This is questionable |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 865 | encoding = sys.getfilesystemencoding() or "latin-1" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 866 | |
| 867 | self.buffer = buffer |
| 868 | self._encoding = encoding |
| 869 | self._newline = newline or os.linesep |
| 870 | self._fix_newlines = newline is None |
| 871 | self._decoder = None |
| 872 | self._pending = '' |
| 873 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 874 | def flush(self): |
| 875 | self.buffer.flush() |
| 876 | |
| 877 | def close(self): |
| 878 | self.flush() |
| 879 | self.buffer.close() |
| 880 | |
| 881 | @property |
| 882 | def closed(self): |
| 883 | return self.buffer.closed |
| 884 | |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 885 | def fileno(self): |
| 886 | return self.buffer.fileno() |
| 887 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 888 | def write(self, s: str): |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 889 | b = s.encode(self._encoding) |
| 890 | if isinstance(b, str): |
| 891 | b = bytes(b) |
| 892 | n = self.buffer.write(b) |
| 893 | if "\n" in s: |
| 894 | self.flush() |
| 895 | return n |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 896 | |
| 897 | def _get_decoder(self): |
| 898 | make_decoder = codecs.getincrementaldecoder(self._encoding) |
| 899 | if make_decoder is None: |
| 900 | raise IOError(".readline() not supported for encoding %s" % |
| 901 | self._encoding) |
| 902 | decoder = self._decoder = make_decoder() # XXX: errors |
| 903 | if isinstance(decoder, codecs.BufferedIncrementalDecoder): |
| 904 | # XXX Hack: make the codec use bytes instead of strings |
| 905 | decoder.buffer = b"" |
| 906 | return decoder |
| 907 | |
| 908 | def read(self, n: int = -1): |
| 909 | decoder = self._decoder or self._get_decoder() |
| 910 | res = self._pending |
| 911 | if n < 0: |
| 912 | res += decoder.decode(self.buffer.read(), True) |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 913 | self._pending = "" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 914 | return res |
| 915 | else: |
| 916 | while len(res) < n: |
| 917 | data = self.buffer.read(64) |
| 918 | res += decoder.decode(data, not data) |
| 919 | if not data: |
| 920 | break |
| 921 | self._pending = res[n:] |
| 922 | return res[:n] |
| 923 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 924 | def readline(self, limit=None): |
| 925 | if limit is not None: |
| 926 | # XXX Hack to support limit arg |
| 927 | line = self.readline() |
| 928 | if len(line) <= limit: |
| 929 | return line |
| 930 | line, self._pending = line[:limit], line[limit:] + self._pending |
| 931 | return line |
| 932 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 933 | line = self._pending |
| 934 | start = 0 |
| 935 | decoder = self._decoder or self._get_decoder() |
| 936 | |
| 937 | while True: |
| 938 | # In C we'd look for these in parallel of course. |
| 939 | nlpos = line.find("\n", start) |
| 940 | crpos = line.find("\r", start) |
| 941 | if nlpos >= 0 and crpos >= 0: |
| 942 | endpos = min(nlpos, crpos) |
| 943 | else: |
| 944 | endpos = nlpos if nlpos >= 0 else crpos |
| 945 | |
| 946 | if endpos != -1: |
| 947 | endc = line[endpos] |
| 948 | if endc == "\n": |
| 949 | ending = "\n" |
| 950 | break |
| 951 | |
| 952 | # We've seen \r - is it standalone, \r\n or \r at end of line? |
| 953 | if endpos + 1 < len(line): |
| 954 | if line[endpos+1] == '\n': |
| 955 | ending = "\r\n" |
| 956 | else: |
| 957 | ending = "\r" |
| 958 | break |
| 959 | # There might be a following \n in the next block of data ... |
| 960 | start = endpos |
| 961 | else: |
| 962 | start = len(line) |
| 963 | |
| 964 | # No line ending seen yet - get more data |
| 965 | while True: |
| 966 | data = self.buffer.read(64) |
| 967 | more_line = decoder.decode(data, not data) |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 968 | if more_line or not data: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 969 | break |
| 970 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 971 | if not more_line: |
| 972 | ending = "" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 973 | endpos = len(line) |
| 974 | break |
| 975 | |
| 976 | line += more_line |
| 977 | |
| 978 | nextpos = endpos + len(ending) |
| 979 | self._pending = line[nextpos:] |
| 980 | |
| 981 | # XXX Update self.newlines here if we want to support that |
| 982 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 983 | if self._fix_newlines and ending not in ("\n", ""): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 984 | return line[:endpos] + "\n" |
| 985 | else: |
| 986 | return line[:nextpos] |