blob: df224e68704cb144e4e5e2edc15e9c45fe6494e8 [file] [log] [blame]
Guido van Rossum53807da2007-04-10 19:01:47 +00001"""New I/O library conforming to PEP 3116.
Guido van Rossum28524c72007-02-27 05:47:44 +00002
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00003This is a prototype; hopefully eventually some of this will be
4reimplemented in C.
Guido van Rossum17e43e52007-02-27 15:45:13 +00005
Guido van Rossum53807da2007-04-10 19:01:47 +00006Conformance of alternative implementations: all arguments are intended
7to be positional-only except the arguments of the open() function.
8Argument names except those of the open() function are not part of the
9specification. Instance variables and methods whose name starts with
10a leading underscore are not part of the specification (except "magic"
11names like __iter__). Only the top-level names listed in the __all__
12variable are part of the specification.
Guido van Rossumc819dea2007-03-15 18:59:31 +000013
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +000014XXX edge cases when switching between reading/writing
Guido van Rossumc819dea2007-03-15 18:59:31 +000015XXX need to default buffer size to 1 if isatty()
16XXX need to support 1 meaning line-buffered
Guido van Rossum76c5d4d2007-04-06 19:10:29 +000017XXX don't use assert to validate input requirements
Guido van Rossum9b76da62007-04-11 01:09:03 +000018XXX whenever an argument is None, use the default value
19XXX read/write ops should check readable/writable
Guido van Rossumd4103952007-04-12 05:44:49 +000020XXX buffered readinto should work with arbitrary buffer objects
Guido van Rossumd76e7792007-04-17 02:38:04 +000021XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG
Guido van Rossum28524c72007-02-27 05:47:44 +000022"""
23
Guido van Rossum68bbcd22007-02-27 17:19:33 +000024__author__ = ("Guido van Rossum <guido@python.org>, "
Guido van Rossum78892e42007-04-06 17:31:18 +000025 "Mike Verdone <mike.verdone@gmail.com>, "
26 "Mark Russell <mark.russell@zen.co.uk>")
Guido van Rossum28524c72007-02-27 05:47:44 +000027
Guido van Rossum141f7672007-04-10 00:22:16 +000028__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
29 "SocketIO", "BytesIO", "StringIO", "BufferedIOBase",
Guido van Rossum01a27522007-03-07 01:00:12 +000030 "BufferedReader", "BufferedWriter", "BufferedRWPair",
Guido van Rossum141f7672007-04-10 00:22:16 +000031 "BufferedRandom", "TextIOBase", "TextIOWrapper"]
Guido van Rossum28524c72007-02-27 05:47:44 +000032
33import os
Guido van Rossum78892e42007-04-06 17:31:18 +000034import sys
35import codecs
Guido van Rossum141f7672007-04-10 00:22:16 +000036import _fileio
Guido van Rossum78892e42007-04-06 17:31:18 +000037import warnings
Guido van Rossum28524c72007-02-27 05:47:44 +000038
Guido van Rossum9b76da62007-04-11 01:09:03 +000039# XXX Shouldn't we use st_blksize whenever we can?
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000040DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
Guido van Rossum01a27522007-03-07 01:00:12 +000041
42
Guido van Rossum141f7672007-04-10 00:22:16 +000043class BlockingIOError(IOError):
Guido van Rossum78892e42007-04-06 17:31:18 +000044
Guido van Rossum141f7672007-04-10 00:22:16 +000045 """Exception raised when I/O would block on a non-blocking I/O stream."""
46
47 def __init__(self, errno, strerror, characters_written=0):
Guido van Rossum01a27522007-03-07 01:00:12 +000048 IOError.__init__(self, errno, strerror)
49 self.characters_written = characters_written
50
Guido van Rossum68bbcd22007-02-27 17:19:33 +000051
Guido van Rossum9b76da62007-04-11 01:09:03 +000052def open(file, mode="r", buffering=None, *, encoding=None, newline=None):
Guido van Rossum17e43e52007-02-27 15:45:13 +000053 """Replacement for the built-in open function.
54
55 Args:
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000056 file: string giving the name of the file to be opened;
Guido van Rossum9b76da62007-04-11 01:09:03 +000057 or integer file descriptor of the file to be wrapped (*).
58 mode: optional mode string; see below.
Guido van Rossum17e43e52007-02-27 15:45:13 +000059 buffering: optional int >= 0 giving the buffer size; values
60 can be: 0 = unbuffered, 1 = line buffered,
Guido van Rossum9b76da62007-04-11 01:09:03 +000061 larger = fully buffered.
62 Keywords (for text modes only; *must* be given as keyword arguments):
63 encoding: optional string giving the text encoding.
64 newline: optional newlines specifier; must be None, '\n' or '\r\n';
65 specifies the line ending expected on input and written on
66 output. If None, use universal newlines on input and
67 use os.linesep on output.
Guido van Rossum17e43e52007-02-27 15:45:13 +000068
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000069 (*) If a file descriptor is given, it is closed when the returned
70 I/O object is closed. If you don't want this to happen, use
71 os.dup() to create a duplicate file descriptor.
72
Guido van Rossum17e43e52007-02-27 15:45:13 +000073 Mode strings characters:
74 'r': open for reading (default)
75 'w': open for writing, truncating the file first
76 'a': open for writing, appending to the end if the file exists
77 'b': binary mode
78 't': text mode (default)
79 '+': open a disk file for updating (implies reading and writing)
Guido van Rossum9be55972007-04-07 02:59:27 +000080 'U': universal newline mode (for backwards compatibility)
Guido van Rossum17e43e52007-02-27 15:45:13 +000081
82 Constraints:
83 - encoding must not be given when a binary mode is given
84 - buffering must not be zero when a text mode is given
85
86 Returns:
87 Depending on the mode and buffering arguments, either a raw
88 binary stream, a buffered binary stream, or a buffered text
89 stream, open for reading and/or writing.
90 """
Guido van Rossum9b76da62007-04-11 01:09:03 +000091 # XXX Don't use asserts for these checks; raise TypeError or ValueError
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000092 assert isinstance(file, (basestring, int)), repr(file)
93 assert isinstance(mode, basestring), repr(mode)
94 assert buffering is None or isinstance(buffering, int), repr(buffering)
95 assert encoding is None or isinstance(encoding, basestring), repr(encoding)
Guido van Rossum28524c72007-02-27 05:47:44 +000096 modes = set(mode)
Guido van Rossum9be55972007-04-07 02:59:27 +000097 if modes - set("arwb+tU") or len(mode) > len(modes):
Guido van Rossum28524c72007-02-27 05:47:44 +000098 raise ValueError("invalid mode: %r" % mode)
99 reading = "r" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000100 writing = "w" in modes
Guido van Rossum28524c72007-02-27 05:47:44 +0000101 appending = "a" in modes
102 updating = "+" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000103 text = "t" in modes
104 binary = "b" in modes
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000105 if "U" in modes and not (reading or writing or appending):
Guido van Rossum9be55972007-04-07 02:59:27 +0000106 reading = True
Guido van Rossum28524c72007-02-27 05:47:44 +0000107 if text and binary:
108 raise ValueError("can't have text and binary mode at once")
109 if reading + writing + appending > 1:
110 raise ValueError("can't have read/write/append mode at once")
111 if not (reading or writing or appending):
112 raise ValueError("must have exactly one of read/write/append mode")
113 if binary and encoding is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +0000114 raise ValueError("binary mode doesn't take an encoding argument")
115 if binary and newline is not None:
116 raise ValueError("binary mode doesn't take a newline argument")
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000117 raw = FileIO(file,
Guido van Rossum28524c72007-02-27 05:47:44 +0000118 (reading and "r" or "") +
119 (writing and "w" or "") +
120 (appending and "a" or "") +
121 (updating and "+" or ""))
122 if buffering is None:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000123 buffering = -1
124 if buffering < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000125 buffering = DEFAULT_BUFFER_SIZE
126 # XXX Should default to line buffering if os.isatty(raw.fileno())
Guido van Rossum17e43e52007-02-27 15:45:13 +0000127 try:
128 bs = os.fstat(raw.fileno()).st_blksize
129 except (os.error, AttributeError):
Guido van Rossumbb09b212007-03-18 03:36:28 +0000130 pass
131 else:
Guido van Rossum17e43e52007-02-27 15:45:13 +0000132 if bs > 1:
133 buffering = bs
Guido van Rossum28524c72007-02-27 05:47:44 +0000134 if buffering < 0:
135 raise ValueError("invalid buffering size")
136 if buffering == 0:
137 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000138 raw._name = file
139 raw._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000140 return raw
141 raise ValueError("can't have unbuffered text I/O")
142 if updating:
143 buffer = BufferedRandom(raw, buffering)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000144 elif writing or appending:
Guido van Rossum28524c72007-02-27 05:47:44 +0000145 buffer = BufferedWriter(raw, buffering)
146 else:
147 assert reading
148 buffer = BufferedReader(raw, buffering)
149 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000150 buffer.name = file
151 buffer.mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000152 return buffer
Guido van Rossum13633bb2007-04-13 18:42:35 +0000153 text = TextIOWrapper(buffer, encoding, newline)
154 text.name = file
155 text.mode = mode
156 return text
Guido van Rossum28524c72007-02-27 05:47:44 +0000157
158
Guido van Rossum141f7672007-04-10 00:22:16 +0000159class IOBase:
Guido van Rossum28524c72007-02-27 05:47:44 +0000160
Guido van Rossum141f7672007-04-10 00:22:16 +0000161 """Base class for all I/O classes.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000162
Guido van Rossum141f7672007-04-10 00:22:16 +0000163 This class provides dummy implementations for many methods that
Guido van Rossum17e43e52007-02-27 15:45:13 +0000164 derived classes can override selectively; the default
165 implementations represent a file that cannot be read, written or
166 seeked.
167
Guido van Rossum141f7672007-04-10 00:22:16 +0000168 This does not define read(), readinto() and write(), nor
169 readline() and friends, since their signatures vary per layer.
Guido van Rossum53807da2007-04-10 19:01:47 +0000170
171 Not that calling any method (even inquiries) on a closed file is
172 undefined. Implementations may raise IOError in this case.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000173 """
174
Guido van Rossum141f7672007-04-10 00:22:16 +0000175 ### Internal ###
176
177 def _unsupported(self, name: str) -> IOError:
178 """Internal: raise an exception for unsupported operations."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000179 raise IOError("%s.%s() not supported" % (self.__class__.__name__,
180 name))
181
Guido van Rossum141f7672007-04-10 00:22:16 +0000182 ### Positioning ###
183
Guido van Rossum53807da2007-04-10 19:01:47 +0000184 def seek(self, pos: int, whence: int = 0) -> int:
185 """seek(pos: int, whence: int = 0) -> int. Change stream position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000186
187 Seek to byte offset pos relative to position indicated by whence:
188 0 Start of stream (the default). pos should be >= 0;
189 1 Current position - whence may be negative;
190 2 End of stream - whence usually negative.
Guido van Rossum53807da2007-04-10 19:01:47 +0000191 Returns the new absolute position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000192 """
193 self._unsupported("seek")
194
195 def tell(self) -> int:
196 """tell() -> int. Return current stream position."""
Guido van Rossum53807da2007-04-10 19:01:47 +0000197 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000198
Guido van Rossum87429772007-04-10 21:06:59 +0000199 def truncate(self, pos: int = None) -> int:
200 """truncate(size: int = None) -> int. Truncate file to size bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000201
202 Size defaults to the current IO position as reported by tell().
Guido van Rossum87429772007-04-10 21:06:59 +0000203 Returns the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000204 """
205 self._unsupported("truncate")
206
207 ### Flush and close ###
208
209 def flush(self) -> None:
210 """flush() -> None. Flushes write buffers, if applicable.
211
212 This is a no-op for read-only and non-blocking streams.
213 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000214 # XXX Should this return the number of bytes written???
Guido van Rossum141f7672007-04-10 00:22:16 +0000215
216 __closed = False
217
218 def close(self) -> None:
219 """close() -> None. Flushes and closes the IO object.
220
221 This must be idempotent. It should also set a flag for the
222 'closed' property (see below) to test.
223 """
224 if not self.__closed:
225 self.__closed = True
226 self.flush()
227
228 def __del__(self) -> None:
229 """Destructor. Calls close()."""
230 # The try/except block is in case this is called at program
231 # exit time, when it's possible that globals have already been
232 # deleted, and then the close() call might fail. Since
233 # there's nothing we can do about such failures and they annoy
234 # the end users, we suppress the traceback.
235 try:
236 self.close()
237 except:
238 pass
239
240 ### Inquiries ###
241
242 def seekable(self) -> bool:
243 """seekable() -> bool. Return whether object supports random access.
244
245 If False, seek(), tell() and truncate() will raise IOError.
246 This method may need to do a test seek().
247 """
248 return False
249
250 def readable(self) -> bool:
251 """readable() -> bool. Return whether object was opened for reading.
252
253 If False, read() will raise IOError.
254 """
255 return False
256
257 def writable(self) -> bool:
258 """writable() -> bool. Return whether object was opened for writing.
259
260 If False, write() and truncate() will raise IOError.
261 """
262 return False
263
264 @property
265 def closed(self):
266 """closed: bool. True iff the file has been closed.
267
268 For backwards compatibility, this is a property, not a predicate.
269 """
270 return self.__closed
271
272 ### Context manager ###
273
274 def __enter__(self) -> "IOBase": # That's a forward reference
275 """Context management protocol. Returns self."""
276 return self
277
278 def __exit__(self, *args) -> None:
279 """Context management protocol. Calls close()"""
280 self.close()
281
282 ### Lower-level APIs ###
283
284 # XXX Should these be present even if unimplemented?
285
286 def fileno(self) -> int:
287 """fileno() -> int. Returns underlying file descriptor if one exists.
288
289 Raises IOError if the IO object does not use a file descriptor.
290 """
291 self._unsupported("fileno")
292
293 def isatty(self) -> bool:
294 """isatty() -> int. Returns whether this is an 'interactive' stream.
295
296 Returns False if we don't know.
297 """
298 return False
299
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000300 ### Readline ###
301
302 def readline(self, sizehint: int = -1) -> bytes:
303 """For backwards compatibility, a (slow) readline()."""
304 if sizehint is None:
305 sizehint = -1
306 res = b""
307 while sizehint < 0 or len(res) < sizehint:
308 b = self.read(1)
309 if not b:
310 break
311 res += b
312 if b == b"\n":
313 break
314 return res
315
Guido van Rossum141f7672007-04-10 00:22:16 +0000316
317class RawIOBase(IOBase):
318
319 """Base class for raw binary I/O.
320
321 The read() method is implemented by calling readinto(); derived
322 classes that want to support read() only need to implement
323 readinto() as a primitive operation. In general, readinto()
324 can be more efficient than read().
325
326 (It would be tempting to also provide an implementation of
327 readinto() in terms of read(), in case the latter is a more
328 suitable primitive operation, but that would lead to nasty
329 recursion in case a subclass doesn't implement either.)
330 """
331
332 def read(self, n: int) -> bytes:
Guido van Rossum78892e42007-04-06 17:31:18 +0000333 """read(n: int) -> bytes. Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000334
335 Returns an empty bytes array on EOF, or None if the object is
336 set not to block and has no data to read.
337 """
Guido van Rossum28524c72007-02-27 05:47:44 +0000338 b = bytes(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000339 n = self.readinto(b)
340 del b[n:]
Guido van Rossum28524c72007-02-27 05:47:44 +0000341 return b
342
Guido van Rossum141f7672007-04-10 00:22:16 +0000343 def readinto(self, b: bytes) -> int:
344 """readinto(b: bytes) -> int. Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000345
346 Returns number of bytes read (0 for EOF), or None if the object
347 is set not to block as has no data to read.
348 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000349 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000350
Guido van Rossum141f7672007-04-10 00:22:16 +0000351 def write(self, b: bytes) -> int:
Guido van Rossum78892e42007-04-06 17:31:18 +0000352 """write(b: bytes) -> int. Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000353
Guido van Rossum78892e42007-04-06 17:31:18 +0000354 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000355 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000356 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000357
Guido van Rossum78892e42007-04-06 17:31:18 +0000358
Guido van Rossum141f7672007-04-10 00:22:16 +0000359class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000360
Guido van Rossum141f7672007-04-10 00:22:16 +0000361 """Raw I/O implementation for OS files.
Guido van Rossum28524c72007-02-27 05:47:44 +0000362
Guido van Rossum141f7672007-04-10 00:22:16 +0000363 This multiply inherits from _FileIO and RawIOBase to make
364 isinstance(io.FileIO(), io.RawIOBase) return True without
365 requiring that _fileio._FileIO inherits from io.RawIOBase (which
366 would be hard to do since _fileio.c is written in C).
367 """
Guido van Rossuma9e20242007-03-08 00:43:48 +0000368
Guido van Rossum87429772007-04-10 21:06:59 +0000369 def close(self):
370 _fileio._FileIO.close(self)
371 RawIOBase.close(self)
372
Guido van Rossum13633bb2007-04-13 18:42:35 +0000373 @property
374 def name(self):
375 return self._name
376
377 @property
378 def mode(self):
379 return self._mode
380
Guido van Rossuma9e20242007-03-08 00:43:48 +0000381
Guido van Rossum28524c72007-02-27 05:47:44 +0000382class SocketIO(RawIOBase):
383
384 """Raw I/O implementation for stream sockets."""
385
Guido van Rossum17e43e52007-02-27 15:45:13 +0000386 # XXX More docs
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000387
Guido van Rossum28524c72007-02-27 05:47:44 +0000388 def __init__(self, sock, mode):
389 assert mode in ("r", "w", "rw")
Guido van Rossum141f7672007-04-10 00:22:16 +0000390 RawIOBase.__init__(self)
Guido van Rossum28524c72007-02-27 05:47:44 +0000391 self._sock = sock
392 self._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000393
394 def readinto(self, b):
395 return self._sock.recv_into(b)
396
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000397 def read(self, n: int = None) -> bytes:
398 """read(n: int) -> bytes. Read and return up to n bytes.
399
400 Returns an empty bytes array on EOF, or None if the object is
401 set not to block and has no data to read.
402 """
403 if n is None:
404 n = -1
405 if n >= 0:
406 return RawIOBase.read(self, n)
407 # Support reading until the end.
408 # XXX Why doesn't RawIOBase support this?
409 data = b""
410 while True:
411 more = RawIOBase.read(self, DEFAULT_BUFFER_SIZE)
412 if not more:
413 break
414 data += more
415 return data
416
Guido van Rossum28524c72007-02-27 05:47:44 +0000417 def write(self, b):
418 return self._sock.send(b)
419
420 def close(self):
Guido van Rossum141f7672007-04-10 00:22:16 +0000421 if not self.closed:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000422 RawIOBase.close(self)
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000423
Guido van Rossum28524c72007-02-27 05:47:44 +0000424 def readable(self):
425 return "r" in self._mode
426
427 def writable(self):
428 return "w" in self._mode
429
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000430 def fileno(self):
431 return self._sock.fileno()
Neal Norwitz8b41c3d2007-02-27 06:26:14 +0000432
Guido van Rossum28524c72007-02-27 05:47:44 +0000433
Guido van Rossumcce92b22007-04-10 14:41:39 +0000434class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000435
436 """Base class for buffered IO objects.
437
438 The main difference with RawIOBase is that the read() method
439 supports omitting the size argument, and does not have a default
440 implementation that defers to readinto().
441
442 In addition, read(), readinto() and write() may raise
443 BlockingIOError if the underlying raw stream is in non-blocking
444 mode and not ready; unlike their raw counterparts, they will never
445 return None.
446
447 A typical implementation should not inherit from a RawIOBase
448 implementation, but wrap one.
449 """
450
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000451 def read(self, n: int = None) -> bytes:
452 """read(n: int = None) -> bytes. Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000453
Guido van Rossum024da5c2007-05-17 23:59:11 +0000454 If the argument is omitted, None, or negative, reads and
455 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000456
457 If the argument is positive, and the underlying raw stream is
458 not 'interactive', multiple raw reads may be issued to satisfy
459 the byte count (unless EOF is reached first). But for
460 interactive raw streams (XXX and for pipes?), at most one raw
461 read will be issued, and a short result does not imply that
462 EOF is imminent.
463
464 Returns an empty bytes array on EOF.
465
466 Raises BlockingIOError if the underlying raw stream has no
467 data at the moment.
468 """
469 self._unsupported("read")
470
471 def readinto(self, b: bytes) -> int:
472 """readinto(b: bytes) -> int. Read up to len(b) bytes into b.
473
474 Like read(), this may issue multiple reads to the underlying
475 raw stream, unless the latter is 'interactive' (XXX or a
476 pipe?).
477
478 Returns the number of bytes read (0 for EOF).
479
480 Raises BlockingIOError if the underlying raw stream has no
481 data at the moment.
482 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000483 # XXX This ought to work with anything that supports the buffer API
Guido van Rossum87429772007-04-10 21:06:59 +0000484 data = self.read(len(b))
485 n = len(data)
486 b[:n] = data
487 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000488
489 def write(self, b: bytes) -> int:
490 """write(b: bytes) -> int. Write the given buffer to the IO stream.
491
492 Returns the number of bytes written, which is never less than
493 len(b).
494
495 Raises BlockingIOError if the buffer is full and the
496 underlying raw stream cannot accept more data at the moment.
497 """
498 self._unsupported("write")
499
500
501class _BufferedIOMixin(BufferedIOBase):
502
503 """A mixin implementation of BufferedIOBase with an underlying raw stream.
504
505 This passes most requests on to the underlying raw stream. It
506 does *not* provide implementations of read(), readinto() or
507 write().
508 """
509
510 def __init__(self, raw):
511 self.raw = raw
512
513 ### Positioning ###
514
515 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000516 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000517
518 def tell(self):
519 return self.raw.tell()
520
521 def truncate(self, pos=None):
Guido van Rossum87429772007-04-10 21:06:59 +0000522 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000523
524 ### Flush and close ###
525
526 def flush(self):
527 self.raw.flush()
528
529 def close(self):
530 self.flush()
531 self.raw.close()
532
533 ### Inquiries ###
534
535 def seekable(self):
536 return self.raw.seekable()
537
538 def readable(self):
539 return self.raw.readable()
540
541 def writable(self):
542 return self.raw.writable()
543
544 @property
545 def closed(self):
546 return self.raw.closed
547
548 ### Lower-level APIs ###
549
550 def fileno(self):
551 return self.raw.fileno()
552
553 def isatty(self):
554 return self.raw.isatty()
555
556
Guido van Rossum024da5c2007-05-17 23:59:11 +0000557class BytesIO(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000558
Guido van Rossum024da5c2007-05-17 23:59:11 +0000559 """Buffered I/O implementation using an in-memory bytes buffer."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000560
Guido van Rossum024da5c2007-05-17 23:59:11 +0000561 # XXX More docs
562
563 def __init__(self, initial_bytes=None):
564 buffer = b""
565 if initial_bytes is not None:
566 buffer += initial_bytes
Guido van Rossum78892e42007-04-06 17:31:18 +0000567 self._buffer = buffer
Guido van Rossum28524c72007-02-27 05:47:44 +0000568 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000569
570 def getvalue(self):
571 return self._buffer
572
Guido van Rossum024da5c2007-05-17 23:59:11 +0000573 def read(self, n=None):
574 if n is None:
575 n = -1
Guido van Rossum141f7672007-04-10 00:22:16 +0000576 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000577 n = len(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000578 newpos = min(len(self._buffer), self._pos + n)
579 b = self._buffer[self._pos : newpos]
580 self._pos = newpos
581 return b
582
Guido van Rossum024da5c2007-05-17 23:59:11 +0000583 def read1(self, n):
584 return self.read(n)
585
Guido van Rossum28524c72007-02-27 05:47:44 +0000586 def write(self, b):
587 n = len(b)
588 newpos = self._pos + n
589 self._buffer[self._pos:newpos] = b
590 self._pos = newpos
591 return n
592
593 def seek(self, pos, whence=0):
594 if whence == 0:
595 self._pos = max(0, pos)
596 elif whence == 1:
597 self._pos = max(0, self._pos + pos)
598 elif whence == 2:
599 self._pos = max(0, len(self._buffer) + pos)
600 else:
601 raise IOError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000602 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000603
604 def tell(self):
605 return self._pos
606
607 def truncate(self, pos=None):
608 if pos is None:
609 pos = self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000610 del self._buffer[pos:]
Guido van Rossum87429772007-04-10 21:06:59 +0000611 return pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000612
613 def readable(self):
614 return True
615
616 def writable(self):
617 return True
618
619 def seekable(self):
620 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000621
622
Guido van Rossum141f7672007-04-10 00:22:16 +0000623class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000624
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000625 """Buffer for a readable sequential RawIO object."""
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000626
Guido van Rossum78892e42007-04-06 17:31:18 +0000627 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000628 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000629 """
630 assert raw.readable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000631 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum01a27522007-03-07 01:00:12 +0000632 self._read_buf = b""
Guido van Rossum78892e42007-04-06 17:31:18 +0000633 self.buffer_size = buffer_size
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000634
Guido van Rossum024da5c2007-05-17 23:59:11 +0000635 def read(self, n=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000636 """Read n bytes.
637
638 Returns exactly n bytes of data unless the underlying raw IO
Walter Dörwalda3270002007-05-29 19:13:29 +0000639 stream reaches EOF or if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000640 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000641 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000642 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000643 if n is None:
644 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +0000645 nodata_val = b""
Guido van Rossum141f7672007-04-10 00:22:16 +0000646 while n < 0 or len(self._read_buf) < n:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000647 to_read = max(self.buffer_size,
648 n if n is not None else 2*len(self._read_buf))
Guido van Rossum78892e42007-04-06 17:31:18 +0000649 current = self.raw.read(to_read)
Guido van Rossum78892e42007-04-06 17:31:18 +0000650 if current in (b"", None):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000651 nodata_val = current
652 break
Guido van Rossum01a27522007-03-07 01:00:12 +0000653 self._read_buf += current
654 if self._read_buf:
Guido van Rossum141f7672007-04-10 00:22:16 +0000655 if n < 0:
Guido van Rossum01a27522007-03-07 01:00:12 +0000656 n = len(self._read_buf)
657 out = self._read_buf[:n]
658 self._read_buf = self._read_buf[n:]
659 else:
660 out = nodata_val
661 return out
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000662
Guido van Rossum13633bb2007-04-13 18:42:35 +0000663 def peek(self, n=0, *, unsafe=False):
664 """Returns buffered bytes without advancing the position.
665
666 The argument indicates a desired minimal number of bytes; we
667 do at most one raw read to satisfy it. We never return more
668 than self.buffer_size.
669
670 Unless unsafe=True is passed, we return a copy.
671 """
672 want = min(n, self.buffer_size)
673 have = len(self._read_buf)
674 if have < want:
675 to_read = self.buffer_size - have
676 current = self.raw.read(to_read)
677 if current:
678 self._read_buf += current
679 result = self._read_buf
680 if unsafe:
681 result = result[:]
682 return result
683
684 def read1(self, n):
685 """Reads up to n bytes.
686
687 Returns up to n bytes. If at least one byte is buffered,
688 we only return buffered bytes. Otherwise, we do one
689 raw read.
690 """
691 if n <= 0:
692 return b""
693 self.peek(1, unsafe=True)
694 return self.read(min(n, len(self._read_buf)))
695
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000696 def tell(self):
697 return self.raw.tell() - len(self._read_buf)
698
699 def seek(self, pos, whence=0):
700 if whence == 1:
701 pos -= len(self._read_buf)
Guido van Rossum53807da2007-04-10 19:01:47 +0000702 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000703 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +0000704 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000705
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000706
Guido van Rossum141f7672007-04-10 00:22:16 +0000707class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000708
Guido van Rossum78892e42007-04-06 17:31:18 +0000709 # XXX docstring
710
Guido van Rossum141f7672007-04-10 00:22:16 +0000711 def __init__(self, raw,
712 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000713 assert raw.writable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000714 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000715 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +0000716 self.max_buffer_size = (2*buffer_size
717 if max_buffer_size is None
718 else max_buffer_size)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000719 self._write_buf = b""
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000720
721 def write(self, b):
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000722 if not isinstance(b, bytes):
723 b = bytes(b)
Guido van Rossum01a27522007-03-07 01:00:12 +0000724 # XXX we can implement some more tricks to try and avoid partial writes
Guido van Rossum01a27522007-03-07 01:00:12 +0000725 if len(self._write_buf) > self.buffer_size:
726 # We're full, so let's pre-flush the buffer
727 try:
728 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000729 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000730 # We can't accept anything else.
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000731 # XXX Why not just let the exception pass through?
Guido van Rossum141f7672007-04-10 00:22:16 +0000732 raise BlockingIOError(e.errno, e.strerror, 0)
Guido van Rossumd4103952007-04-12 05:44:49 +0000733 before = len(self._write_buf)
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000734 self._write_buf.extend(b)
Guido van Rossumd4103952007-04-12 05:44:49 +0000735 written = len(self._write_buf) - before
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000736 if len(self._write_buf) > self.buffer_size:
Guido van Rossum01a27522007-03-07 01:00:12 +0000737 try:
738 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000739 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000740 if (len(self._write_buf) > self.max_buffer_size):
741 # We've hit max_buffer_size. We have to accept a partial
742 # write and cut back our buffer.
743 overage = len(self._write_buf) - self.max_buffer_size
744 self._write_buf = self._write_buf[:self.max_buffer_size]
Guido van Rossum141f7672007-04-10 00:22:16 +0000745 raise BlockingIOError(e.errno, e.strerror, overage)
Guido van Rossumd4103952007-04-12 05:44:49 +0000746 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000747
748 def flush(self):
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000749 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +0000750 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000751 while self._write_buf:
752 n = self.raw.write(self._write_buf)
753 del self._write_buf[:n]
754 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000755 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000756 n = e.characters_written
757 del self._write_buf[:n]
758 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000759 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000760
761 def tell(self):
762 return self.raw.tell() + len(self._write_buf)
763
764 def seek(self, pos, whence=0):
765 self.flush()
Guido van Rossum53807da2007-04-10 19:01:47 +0000766 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000767
Guido van Rossum01a27522007-03-07 01:00:12 +0000768
Guido van Rossum141f7672007-04-10 00:22:16 +0000769class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000770
Guido van Rossum01a27522007-03-07 01:00:12 +0000771 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000772
Guido van Rossum141f7672007-04-10 00:22:16 +0000773 A buffered reader object and buffered writer object put together
774 to form a sequential IO object that can read and write.
Guido van Rossum78892e42007-04-06 17:31:18 +0000775
776 This is typically used with a socket or two-way pipe.
Guido van Rossum141f7672007-04-10 00:22:16 +0000777
778 XXX The usefulness of this (compared to having two separate IO
779 objects) is questionable.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000780 """
781
Guido van Rossum141f7672007-04-10 00:22:16 +0000782 def __init__(self, reader, writer,
783 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
784 """Constructor.
785
786 The arguments are two RawIO instances.
787 """
Guido van Rossum01a27522007-03-07 01:00:12 +0000788 assert reader.readable()
789 assert writer.writable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000790 self.reader = BufferedReader(reader, buffer_size)
791 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +0000792
Guido van Rossum024da5c2007-05-17 23:59:11 +0000793 def read(self, n=None):
794 if n is None:
795 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +0000796 return self.reader.read(n)
797
Guido van Rossum141f7672007-04-10 00:22:16 +0000798 def readinto(self, b):
799 return self.reader.readinto(b)
800
Guido van Rossum01a27522007-03-07 01:00:12 +0000801 def write(self, b):
802 return self.writer.write(b)
803
Guido van Rossum13633bb2007-04-13 18:42:35 +0000804 def peek(self, n=0, *, unsafe=False):
805 return self.reader.peek(n, unsafe=unsafe)
806
807 def read1(self, n):
808 return self.reader.read1(n)
809
Guido van Rossum01a27522007-03-07 01:00:12 +0000810 def readable(self):
811 return self.reader.readable()
812
813 def writable(self):
814 return self.writer.writable()
815
816 def flush(self):
817 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000818
Guido van Rossum01a27522007-03-07 01:00:12 +0000819 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +0000820 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000821 self.reader.close()
822
823 def isatty(self):
824 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +0000825
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000826 @property
827 def closed(self):
Guido van Rossum141f7672007-04-10 00:22:16 +0000828 return self.writer.closed()
Guido van Rossum01a27522007-03-07 01:00:12 +0000829
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000830
Guido van Rossum141f7672007-04-10 00:22:16 +0000831class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +0000832
Guido van Rossum78892e42007-04-06 17:31:18 +0000833 # XXX docstring
834
Guido van Rossum141f7672007-04-10 00:22:16 +0000835 def __init__(self, raw,
836 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000837 assert raw.seekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000838 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +0000839 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
840
Guido van Rossum01a27522007-03-07 01:00:12 +0000841 def seek(self, pos, whence=0):
842 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000843 # First do the raw seek, then empty the read buffer, so that
844 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +0000845 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000846 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +0000847 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +0000848
849 def tell(self):
850 if (self._write_buf):
851 return self.raw.tell() + len(self._write_buf)
852 else:
853 return self.raw.tell() - len(self._read_buf)
854
Guido van Rossum024da5c2007-05-17 23:59:11 +0000855 def read(self, n=None):
856 if n is None:
857 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +0000858 self.flush()
859 return BufferedReader.read(self, n)
860
Guido van Rossum141f7672007-04-10 00:22:16 +0000861 def readinto(self, b):
862 self.flush()
863 return BufferedReader.readinto(self, b)
864
Guido van Rossum13633bb2007-04-13 18:42:35 +0000865 def peek(self, n=0, *, unsafe=False):
866 self.flush()
867 return BufferedReader.peek(self, n, unsafe=unsafe)
868
869 def read1(self, n):
870 self.flush()
871 return BufferedReader.read1(self, n)
872
Guido van Rossum01a27522007-03-07 01:00:12 +0000873 def write(self, b):
Guido van Rossum78892e42007-04-06 17:31:18 +0000874 if self._read_buf:
875 self.raw.seek(-len(self._read_buf), 1) # Undo readahead
876 self._read_buf = b""
Guido van Rossum01a27522007-03-07 01:00:12 +0000877 return BufferedWriter.write(self, b)
878
Guido van Rossum78892e42007-04-06 17:31:18 +0000879
Guido van Rossumcce92b22007-04-10 14:41:39 +0000880class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +0000881
882 """Base class for text I/O.
883
884 This class provides a character and line based interface to stream I/O.
Guido van Rossum9b76da62007-04-11 01:09:03 +0000885
886 There is no readinto() method, as character strings are immutable.
Guido van Rossum78892e42007-04-06 17:31:18 +0000887 """
888
889 def read(self, n: int = -1) -> str:
890 """read(n: int = -1) -> str. Read at most n characters from stream.
891
892 Read from underlying buffer until we have n characters or we hit EOF.
893 If n is negative or omitted, read until EOF.
894 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000895 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +0000896
Guido van Rossum9b76da62007-04-11 01:09:03 +0000897 def write(self, s: str) -> int:
898 """write(s: str) -> int. Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000899 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +0000900
Guido van Rossum9b76da62007-04-11 01:09:03 +0000901 def truncate(self, pos: int = None) -> int:
902 """truncate(pos: int = None) -> int. Truncate size to pos."""
903 self.flush()
904 if pos is None:
905 pos = self.tell()
906 self.seek(pos)
907 return self.buffer.truncate()
908
Guido van Rossum78892e42007-04-06 17:31:18 +0000909 def readline(self) -> str:
910 """readline() -> str. Read until newline or EOF.
911
912 Returns an empty string if EOF is hit immediately.
913 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000914 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +0000915
Guido van Rossum9b76da62007-04-11 01:09:03 +0000916 def __iter__(self) -> "TextIOBase": # That's a forward reference
Guido van Rossum78892e42007-04-06 17:31:18 +0000917 """__iter__() -> Iterator. Return line iterator (actually just self).
918 """
919 return self
920
Georg Brandla18af4e2007-04-21 15:47:16 +0000921 def __next__(self) -> str:
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000922 """Same as readline() except raises StopIteration on immediate EOF."""
Guido van Rossum78892e42007-04-06 17:31:18 +0000923 line = self.readline()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000924 if not line:
Guido van Rossum78892e42007-04-06 17:31:18 +0000925 raise StopIteration
926 return line
927
Guido van Rossumfc3436b2007-05-24 17:58:06 +0000928 @property
929 def encoding(self):
930 """Subclasses should override."""
931 return None
932
Guido van Rossum9be55972007-04-07 02:59:27 +0000933 # The following are provided for backwards compatibility
934
935 def readlines(self, hint=None):
936 if hint is None:
937 return list(self)
938 n = 0
939 lines = []
940 while not lines or n < hint:
941 line = self.readline()
942 if not line:
943 break
944 lines.append(line)
945 n += len(line)
946 return lines
947
948 def writelines(self, lines):
949 for line in lines:
950 self.write(line)
951
Guido van Rossum78892e42007-04-06 17:31:18 +0000952
953class TextIOWrapper(TextIOBase):
954
955 """Buffered text stream.
956
957 Character and line based layer over a BufferedIOBase object.
958 """
959
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +0000960 _CHUNK_SIZE = 128
Guido van Rossum78892e42007-04-06 17:31:18 +0000961
962 def __init__(self, buffer, encoding=None, newline=None):
Guido van Rossum9b76da62007-04-11 01:09:03 +0000963 if newline not in (None, "\n", "\r\n"):
964 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +0000965 if encoding is None:
966 # XXX This is questionable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000967 encoding = sys.getfilesystemencoding() or "latin-1"
Guido van Rossum78892e42007-04-06 17:31:18 +0000968
969 self.buffer = buffer
970 self._encoding = encoding
971 self._newline = newline or os.linesep
972 self._fix_newlines = newline is None
973 self._decoder = None
Guido van Rossum9b76da62007-04-11 01:09:03 +0000974 self._pending = ""
975 self._snapshot = None
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +0000976 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +0000977
Guido van Rossumfc3436b2007-05-24 17:58:06 +0000978 @property
979 def encoding(self):
980 return self._encoding
981
Guido van Rossum9b76da62007-04-11 01:09:03 +0000982 # A word about _snapshot. This attribute is either None, or a
Guido van Rossumd76e7792007-04-17 02:38:04 +0000983 # tuple (decoder_state, readahead, pending) where decoder_state is
984 # the second (integer) item of the decoder state, readahead is the
985 # chunk of bytes that was read, and pending is the characters that
986 # were rendered by the decoder after feeding it those bytes. We
987 # use this to reconstruct intermediate decoder states in tell().
Guido van Rossum9b76da62007-04-11 01:09:03 +0000988
989 def _seekable(self):
990 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +0000991
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000992 def flush(self):
993 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +0000994 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000995
996 def close(self):
997 self.flush()
998 self.buffer.close()
999
1000 @property
1001 def closed(self):
1002 return self.buffer.closed
1003
Guido van Rossum9be55972007-04-07 02:59:27 +00001004 def fileno(self):
1005 return self.buffer.fileno()
1006
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001007 def isatty(self):
1008 return self.buffer.isatty()
1009
Guido van Rossum78892e42007-04-06 17:31:18 +00001010 def write(self, s: str):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001011 # XXX What if we were just reading?
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001012 b = s.encode(self._encoding)
1013 if isinstance(b, str):
1014 b = bytes(b)
1015 n = self.buffer.write(b)
1016 if "\n" in s:
Guido van Rossum13633bb2007-04-13 18:42:35 +00001017 # XXX only if isatty
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001018 self.flush()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001019 self._snapshot = self._decoder = None
1020 return len(s)
Guido van Rossum78892e42007-04-06 17:31:18 +00001021
1022 def _get_decoder(self):
1023 make_decoder = codecs.getincrementaldecoder(self._encoding)
1024 if make_decoder is None:
Guido van Rossum9b76da62007-04-11 01:09:03 +00001025 raise IOError("Can't find an incremental decoder for encoding %s" %
Guido van Rossum78892e42007-04-06 17:31:18 +00001026 self._encoding)
1027 decoder = self._decoder = make_decoder() # XXX: errors
Guido van Rossum78892e42007-04-06 17:31:18 +00001028 return decoder
1029
Guido van Rossum9b76da62007-04-11 01:09:03 +00001030 def _read_chunk(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001031 assert self._decoder is not None
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001032 if not self._telling:
Guido van Rossum13633bb2007-04-13 18:42:35 +00001033 readahead = self.buffer.read1(self._CHUNK_SIZE)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001034 pending = self._decoder.decode(readahead, not readahead)
1035 return readahead, pending
Guido van Rossumd76e7792007-04-17 02:38:04 +00001036 decoder_buffer, decoder_state = self._decoder.getstate()
Guido van Rossum13633bb2007-04-13 18:42:35 +00001037 readahead = self.buffer.read1(self._CHUNK_SIZE)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001038 pending = self._decoder.decode(readahead, not readahead)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001039 self._snapshot = (decoder_state, decoder_buffer + readahead, pending)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001040 return readahead, pending
Guido van Rossum9b76da62007-04-11 01:09:03 +00001041
1042 def _encode_decoder_state(self, ds, pos):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001043 x = 0
1044 for i in bytes(ds):
1045 x = x<<8 | i
1046 return (x<<64) | pos
1047
1048 def _decode_decoder_state(self, pos):
1049 x, pos = divmod(pos, 1<<64)
1050 if not x:
1051 return None, pos
1052 b = b""
1053 while x:
1054 b.append(x&0xff)
1055 x >>= 8
1056 return str(b[::-1]), pos
1057
1058 def tell(self):
1059 if not self._seekable:
1060 raise IOError("Underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001061 if not self._telling:
1062 raise IOError("Telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001063 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001064 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001065 decoder = self._decoder
1066 if decoder is None or self._snapshot is None:
Guido van Rossum9b76da62007-04-11 01:09:03 +00001067 assert self._pending == ""
Guido van Rossumcba608c2007-04-11 14:19:59 +00001068 return position
1069 decoder_state, readahead, pending = self._snapshot
1070 position -= len(readahead)
1071 needed = len(pending) - len(self._pending)
1072 if not needed:
1073 return self._encode_decoder_state(decoder_state, position)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001074 saved_state = decoder.getstate()
1075 try:
Guido van Rossum2b08b382007-05-08 20:18:39 +00001076 decoder.setstate((b"", decoder_state))
Guido van Rossumd76e7792007-04-17 02:38:04 +00001077 n = 0
1078 bb = bytes(1)
1079 for i, bb[0] in enumerate(readahead):
1080 n += len(decoder.decode(bb))
1081 if n >= needed:
1082 decoder_buffer, decoder_state = decoder.getstate()
1083 return self._encode_decoder_state(
1084 decoder_state,
1085 position + (i+1) - len(decoder_buffer))
1086 raise IOError("Can't reconstruct logical file position")
1087 finally:
1088 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001089
1090 def seek(self, pos, whence=0):
1091 if not self._seekable:
1092 raise IOError("Underlying stream is not seekable")
1093 if whence == 1:
1094 if pos != 0:
1095 raise IOError("Can't do nonzero cur-relative seeks")
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001096 pos = self.tell()
1097 whence = 0
Guido van Rossum9b76da62007-04-11 01:09:03 +00001098 if whence == 2:
1099 if pos != 0:
1100 raise IOError("Can't do nonzero end-relative seeks")
1101 self.flush()
1102 pos = self.buffer.seek(0, 2)
1103 self._snapshot = None
1104 self._pending = ""
1105 self._decoder = None
1106 return pos
1107 if whence != 0:
1108 raise ValueError("Invalid whence (%r, should be 0, 1 or 2)" %
1109 (whence,))
1110 if pos < 0:
1111 raise ValueError("Negative seek position %r" % (pos,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001112 self.flush()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001113 orig_pos = pos
1114 ds, pos = self._decode_decoder_state(pos)
1115 if not ds:
1116 self.buffer.seek(pos)
1117 self._snapshot = None
1118 self._pending = ""
1119 self._decoder = None
1120 return pos
Guido van Rossumd76e7792007-04-17 02:38:04 +00001121 decoder = self._decoder or self._get_decoder()
1122 decoder.set_state(("", ds))
Guido van Rossum9b76da62007-04-11 01:09:03 +00001123 self.buffer.seek(pos)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001124 self._snapshot = (ds, b"", "")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001125 self._pending = ""
Guido van Rossumcba608c2007-04-11 14:19:59 +00001126 self._decoder = decoder
Guido van Rossum9b76da62007-04-11 01:09:03 +00001127 return orig_pos
1128
Guido van Rossum024da5c2007-05-17 23:59:11 +00001129 def read(self, n=None):
1130 if n is None:
1131 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001132 decoder = self._decoder or self._get_decoder()
1133 res = self._pending
1134 if n < 0:
1135 res += decoder.decode(self.buffer.read(), True)
Guido van Rossum141f7672007-04-10 00:22:16 +00001136 self._pending = ""
Guido van Rossum9b76da62007-04-11 01:09:03 +00001137 self._snapshot = None
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001138 return res.replace("\r\n", "\n")
Guido van Rossum78892e42007-04-06 17:31:18 +00001139 else:
1140 while len(res) < n:
Guido van Rossumcba608c2007-04-11 14:19:59 +00001141 readahead, pending = self._read_chunk()
1142 res += pending
1143 if not readahead:
Guido van Rossum78892e42007-04-06 17:31:18 +00001144 break
1145 self._pending = res[n:]
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001146 return res[:n].replace("\r\n", "\n")
Guido van Rossum78892e42007-04-06 17:31:18 +00001147
Guido van Rossum024da5c2007-05-17 23:59:11 +00001148 def __next__(self):
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001149 self._telling = False
1150 line = self.readline()
1151 if not line:
1152 self._snapshot = None
1153 self._telling = self._seekable
1154 raise StopIteration
1155 return line
1156
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001157 def readline(self, limit=None):
1158 if limit is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +00001159 # XXX Hack to support limit argument, for backwards compatibility
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001160 line = self.readline()
1161 if len(line) <= limit:
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001162 return line
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001163 line, self._pending = line[:limit], line[limit:] + self._pending
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001164 return line
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001165
Guido van Rossum78892e42007-04-06 17:31:18 +00001166 line = self._pending
1167 start = 0
1168 decoder = self._decoder or self._get_decoder()
1169
1170 while True:
1171 # In C we'd look for these in parallel of course.
1172 nlpos = line.find("\n", start)
1173 crpos = line.find("\r", start)
1174 if nlpos >= 0 and crpos >= 0:
1175 endpos = min(nlpos, crpos)
1176 else:
1177 endpos = nlpos if nlpos >= 0 else crpos
1178
1179 if endpos != -1:
1180 endc = line[endpos]
1181 if endc == "\n":
1182 ending = "\n"
1183 break
1184
1185 # We've seen \r - is it standalone, \r\n or \r at end of line?
1186 if endpos + 1 < len(line):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001187 if line[endpos+1] == "\n":
Guido van Rossum78892e42007-04-06 17:31:18 +00001188 ending = "\r\n"
1189 else:
1190 ending = "\r"
1191 break
1192 # There might be a following \n in the next block of data ...
1193 start = endpos
1194 else:
1195 start = len(line)
1196
1197 # No line ending seen yet - get more data
1198 while True:
Guido van Rossumcba608c2007-04-11 14:19:59 +00001199 readahead, pending = self._read_chunk()
1200 more_line = pending
1201 if more_line or not readahead:
Guido van Rossum78892e42007-04-06 17:31:18 +00001202 break
1203
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001204 if not more_line:
1205 ending = ""
Guido van Rossum78892e42007-04-06 17:31:18 +00001206 endpos = len(line)
1207 break
1208
1209 line += more_line
1210
1211 nextpos = endpos + len(ending)
1212 self._pending = line[nextpos:]
1213
1214 # XXX Update self.newlines here if we want to support that
1215
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001216 if self._fix_newlines and ending not in ("\n", ""):
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001217 return line[:endpos] + "\n"
Guido van Rossum78892e42007-04-06 17:31:18 +00001218 else:
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001219 return line[:nextpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001220
1221
1222class StringIO(TextIOWrapper):
1223
1224 # XXX This is really slow, but fully functional
1225
1226 def __init__(self, initial_value=""):
1227 super(StringIO, self).__init__(BytesIO(), "utf-8")
1228 if initial_value:
1229 self.write(initial_value)
1230 self.seek(0)
1231
1232 def getvalue(self):
1233 return self.buffer.getvalue().decode("utf-8")