blob: 98843d381642468bee7ca9ca83d35d9678596af3 [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 support 1 meaning line-buffered
Guido van Rossum9b76da62007-04-11 01:09:03 +000016XXX whenever an argument is None, use the default value
17XXX read/write ops should check readable/writable
Guido van Rossumd4103952007-04-12 05:44:49 +000018XXX buffered readinto should work with arbitrary buffer objects
Guido van Rossumd76e7792007-04-17 02:38:04 +000019XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG
Guido van Rossum5abbf752007-08-27 17:39:33 +000020XXX check writable, readable and seekable in appropriate places
Guido van Rossum28524c72007-02-27 05:47:44 +000021"""
22
Guido van Rossum68bbcd22007-02-27 17:19:33 +000023__author__ = ("Guido van Rossum <guido@python.org>, "
Guido van Rossum78892e42007-04-06 17:31:18 +000024 "Mike Verdone <mike.verdone@gmail.com>, "
25 "Mark Russell <mark.russell@zen.co.uk>")
Guido van Rossum28524c72007-02-27 05:47:44 +000026
Guido van Rossum141f7672007-04-10 00:22:16 +000027__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
Guido van Rossum5abbf752007-08-27 17:39:33 +000028 "BytesIO", "StringIO", "BufferedIOBase",
Guido van Rossum01a27522007-03-07 01:00:12 +000029 "BufferedReader", "BufferedWriter", "BufferedRWPair",
Guido van Rossum141f7672007-04-10 00:22:16 +000030 "BufferedRandom", "TextIOBase", "TextIOWrapper"]
Guido van Rossum28524c72007-02-27 05:47:44 +000031
32import os
Guido van Rossumb7f136e2007-08-22 18:14:10 +000033import abc
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 Rossum5abbf752007-08-27 17:39:33 +000039# open() uses 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 Rossume7fc50f2007-12-03 22:54:21 +000052def open(file, mode="r", buffering=None, encoding=None, errors=None,
53 newline=None, closefd=True):
Brett Cannon7648ba82007-10-15 20:52:41 +000054 r"""Replacement for the built-in open function.
Guido van Rossum17e43e52007-02-27 15:45:13 +000055
56 Args:
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000057 file: string giving the name of the file to be opened;
Guido van Rossum9b76da62007-04-11 01:09:03 +000058 or integer file descriptor of the file to be wrapped (*).
59 mode: optional mode string; see below.
Guido van Rossum17e43e52007-02-27 15:45:13 +000060 buffering: optional int >= 0 giving the buffer size; values
61 can be: 0 = unbuffered, 1 = line buffered,
Guido van Rossum9b76da62007-04-11 01:09:03 +000062 larger = fully buffered.
Guido van Rossum9b76da62007-04-11 01:09:03 +000063 encoding: optional string giving the text encoding.
Guido van Rossume7fc50f2007-12-03 22:54:21 +000064 errors: optional string giving the encoding error handling.
Guido van Rossum8358db22007-08-18 21:39:55 +000065 newline: optional newlines specifier; must be None, '', '\n', '\r'
66 or '\r\n'; all other values are illegal. It controls the
67 handling of line endings. It works as follows:
68
69 * On input, if `newline` is `None`, universal newlines
70 mode is enabled. Lines in the input can end in `'\n'`,
71 `'\r'`, or `'\r\n'`, and these are translated into
72 `'\n'` before being returned to the caller. If it is
73 `''`, universal newline mode is enabled, but line endings
74 are returned to the caller untranslated. If it has any of
75 the other legal values, input lines are only terminated by
76 the given string, and the line ending is returned to the
77 caller untranslated.
78
79 * On output, if `newline` is `None`, any `'\n'`
80 characters written are translated to the system default
81 line separator, `os.linesep`. If `newline` is `''`,
82 no translation takes place. If `newline` is any of the
83 other legal values, any `'\n'` characters written are
84 translated to the given string.
Guido van Rossum17e43e52007-02-27 15:45:13 +000085
Guido van Rossum2dced8b2007-10-30 17:27:30 +000086 closefd: optional argument to keep the underlying file descriptor
87 open when the file is closed. It must not be false when
88 a filename is given.
89
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000090 (*) If a file descriptor is given, it is closed when the returned
Georg Brandl316414e2007-10-30 17:42:20 +000091 I/O object is closed, unless closefd=False is given.
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000092
Guido van Rossum17e43e52007-02-27 15:45:13 +000093 Mode strings characters:
94 'r': open for reading (default)
95 'w': open for writing, truncating the file first
96 'a': open for writing, appending to the end if the file exists
97 'b': binary mode
98 't': text mode (default)
99 '+': open a disk file for updating (implies reading and writing)
Guido van Rossum9be55972007-04-07 02:59:27 +0000100 'U': universal newline mode (for backwards compatibility)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000101
102 Constraints:
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000103 - encoding or errors must not be given when a binary mode is given
Guido van Rossum17e43e52007-02-27 15:45:13 +0000104 - buffering must not be zero when a text mode is given
105
106 Returns:
107 Depending on the mode and buffering arguments, either a raw
108 binary stream, a buffered binary stream, or a buffered text
109 stream, open for reading and/or writing.
110 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000111 if not isinstance(file, (str, int)):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000112 raise TypeError("invalid file: %r" % file)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000113 if not isinstance(mode, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000114 raise TypeError("invalid mode: %r" % mode)
115 if buffering is not None and not isinstance(buffering, int):
116 raise TypeError("invalid buffering: %r" % buffering)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000117 if encoding is not None and not isinstance(encoding, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000118 raise TypeError("invalid encoding: %r" % encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000119 if errors is not None and not isinstance(errors, str):
120 raise TypeError("invalid errors: %r" % errors)
Guido van Rossum28524c72007-02-27 05:47:44 +0000121 modes = set(mode)
Guido van Rossum9be55972007-04-07 02:59:27 +0000122 if modes - set("arwb+tU") or len(mode) > len(modes):
Guido van Rossum28524c72007-02-27 05:47:44 +0000123 raise ValueError("invalid mode: %r" % mode)
124 reading = "r" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000125 writing = "w" in modes
Guido van Rossum28524c72007-02-27 05:47:44 +0000126 appending = "a" in modes
127 updating = "+" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000128 text = "t" in modes
129 binary = "b" in modes
Guido van Rossum7165cb12007-07-10 06:54:34 +0000130 if "U" in modes:
131 if writing or appending:
132 raise ValueError("can't use U and writing mode at once")
Guido van Rossum9be55972007-04-07 02:59:27 +0000133 reading = True
Guido van Rossum28524c72007-02-27 05:47:44 +0000134 if text and binary:
135 raise ValueError("can't have text and binary mode at once")
136 if reading + writing + appending > 1:
137 raise ValueError("can't have read/write/append mode at once")
138 if not (reading or writing or appending):
139 raise ValueError("must have exactly one of read/write/append mode")
140 if binary and encoding is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +0000141 raise ValueError("binary mode doesn't take an encoding argument")
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000142 if binary and errors is not None:
143 raise ValueError("binary mode doesn't take an errors argument")
Guido van Rossum9b76da62007-04-11 01:09:03 +0000144 if binary and newline is not None:
145 raise ValueError("binary mode doesn't take a newline argument")
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000146 raw = FileIO(file,
Guido van Rossum28524c72007-02-27 05:47:44 +0000147 (reading and "r" or "") +
148 (writing and "w" or "") +
149 (appending and "a" or "") +
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000150 (updating and "+" or ""),
151 closefd)
Guido van Rossum28524c72007-02-27 05:47:44 +0000152 if buffering is None:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000153 buffering = -1
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000154 line_buffering = False
155 if buffering == 1 or buffering < 0 and raw.isatty():
156 buffering = -1
157 line_buffering = True
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000158 if buffering < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000159 buffering = DEFAULT_BUFFER_SIZE
Guido van Rossum17e43e52007-02-27 15:45:13 +0000160 try:
161 bs = os.fstat(raw.fileno()).st_blksize
162 except (os.error, AttributeError):
Guido van Rossumbb09b212007-03-18 03:36:28 +0000163 pass
164 else:
Guido van Rossum17e43e52007-02-27 15:45:13 +0000165 if bs > 1:
166 buffering = bs
Guido van Rossum28524c72007-02-27 05:47:44 +0000167 if buffering < 0:
168 raise ValueError("invalid buffering size")
169 if buffering == 0:
170 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000171 raw._name = file
172 raw._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000173 return raw
174 raise ValueError("can't have unbuffered text I/O")
175 if updating:
176 buffer = BufferedRandom(raw, buffering)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000177 elif writing or appending:
Guido van Rossum28524c72007-02-27 05:47:44 +0000178 buffer = BufferedWriter(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000179 elif reading:
Guido van Rossum28524c72007-02-27 05:47:44 +0000180 buffer = BufferedReader(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000181 else:
182 raise ValueError("unknown mode: %r" % mode)
Guido van Rossum28524c72007-02-27 05:47:44 +0000183 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000184 buffer.name = file
185 buffer.mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000186 return buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000187 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000188 text.name = file
189 text.mode = mode
190 return text
Guido van Rossum28524c72007-02-27 05:47:44 +0000191
Christian Heimesa33eb062007-12-08 17:47:40 +0000192class _DocDescriptor:
193 """Helper for builtins.open.__doc__
194 """
195 def __get__(self, obj, typ):
196 return (
197 "open(file, mode='r', buffering=None, encoding=None, "
198 "errors=None, newline=None, closefd=True)\n\n" +
199 open.__doc__)
Guido van Rossum28524c72007-02-27 05:47:44 +0000200
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000201class OpenWrapper:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000202 """Wrapper for builtins.open
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000203
204 Trick so that open won't become a bound method when stored
205 as a class variable (as dumbdbm does).
206
207 See initstdio() in Python/pythonrun.c.
208 """
Christian Heimesa33eb062007-12-08 17:47:40 +0000209 __doc__ = _DocDescriptor()
210
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000211 def __new__(cls, *args, **kwargs):
212 return open(*args, **kwargs)
213
214
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000215class UnsupportedOperation(ValueError, IOError):
216 pass
217
218
Guido van Rossumb7f136e2007-08-22 18:14:10 +0000219class IOBase(metaclass=abc.ABCMeta):
Guido van Rossum28524c72007-02-27 05:47:44 +0000220
Guido van Rossum141f7672007-04-10 00:22:16 +0000221 """Base class for all I/O classes.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000222
Guido van Rossum141f7672007-04-10 00:22:16 +0000223 This class provides dummy implementations for many methods that
Guido van Rossum17e43e52007-02-27 15:45:13 +0000224 derived classes can override selectively; the default
225 implementations represent a file that cannot be read, written or
226 seeked.
227
Guido van Rossum141f7672007-04-10 00:22:16 +0000228 This does not define read(), readinto() and write(), nor
229 readline() and friends, since their signatures vary per layer.
Guido van Rossum53807da2007-04-10 19:01:47 +0000230
231 Not that calling any method (even inquiries) on a closed file is
232 undefined. Implementations may raise IOError in this case.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000233 """
234
Guido van Rossum141f7672007-04-10 00:22:16 +0000235 ### Internal ###
236
237 def _unsupported(self, name: str) -> IOError:
238 """Internal: raise an exception for unsupported operations."""
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000239 raise UnsupportedOperation("%s.%s() not supported" %
240 (self.__class__.__name__, name))
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000241
Guido van Rossum141f7672007-04-10 00:22:16 +0000242 ### Positioning ###
243
Guido van Rossum53807da2007-04-10 19:01:47 +0000244 def seek(self, pos: int, whence: int = 0) -> int:
245 """seek(pos: int, whence: int = 0) -> int. Change stream position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000246
247 Seek to byte offset pos relative to position indicated by whence:
248 0 Start of stream (the default). pos should be >= 0;
249 1 Current position - whence may be negative;
250 2 End of stream - whence usually negative.
Guido van Rossum53807da2007-04-10 19:01:47 +0000251 Returns the new absolute position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000252 """
253 self._unsupported("seek")
254
255 def tell(self) -> int:
256 """tell() -> int. Return current stream position."""
Guido van Rossum53807da2007-04-10 19:01:47 +0000257 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000258
Guido van Rossum87429772007-04-10 21:06:59 +0000259 def truncate(self, pos: int = None) -> int:
260 """truncate(size: int = None) -> int. Truncate file to size bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000261
262 Size defaults to the current IO position as reported by tell().
Guido van Rossum87429772007-04-10 21:06:59 +0000263 Returns the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000264 """
265 self._unsupported("truncate")
266
267 ### Flush and close ###
268
269 def flush(self) -> None:
270 """flush() -> None. Flushes write buffers, if applicable.
271
272 This is a no-op for read-only and non-blocking streams.
273 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000274 # XXX Should this return the number of bytes written???
Guido van Rossum141f7672007-04-10 00:22:16 +0000275
276 __closed = False
277
278 def close(self) -> None:
279 """close() -> None. Flushes and closes the IO object.
280
281 This must be idempotent. It should also set a flag for the
282 'closed' property (see below) to test.
283 """
284 if not self.__closed:
Guido van Rossum469734b2007-07-10 12:00:45 +0000285 try:
286 self.flush()
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000287 except IOError:
288 pass # If flush() fails, just give up
289 self.__closed = True
Guido van Rossum141f7672007-04-10 00:22:16 +0000290
291 def __del__(self) -> None:
292 """Destructor. Calls close()."""
293 # The try/except block is in case this is called at program
294 # exit time, when it's possible that globals have already been
295 # deleted, and then the close() call might fail. Since
296 # there's nothing we can do about such failures and they annoy
297 # the end users, we suppress the traceback.
298 try:
299 self.close()
300 except:
301 pass
302
303 ### Inquiries ###
304
305 def seekable(self) -> bool:
306 """seekable() -> bool. Return whether object supports random access.
307
308 If False, seek(), tell() and truncate() will raise IOError.
309 This method may need to do a test seek().
310 """
311 return False
312
Guido van Rossum5abbf752007-08-27 17:39:33 +0000313 def _checkSeekable(self, msg=None):
314 """Internal: raise an IOError if file is not seekable
315 """
316 if not self.seekable():
317 raise IOError("File or stream is not seekable."
318 if msg is None else msg)
319
320
Guido van Rossum141f7672007-04-10 00:22:16 +0000321 def readable(self) -> bool:
322 """readable() -> bool. Return whether object was opened for reading.
323
324 If False, read() will raise IOError.
325 """
326 return False
327
Guido van Rossum5abbf752007-08-27 17:39:33 +0000328 def _checkReadable(self, msg=None):
329 """Internal: raise an IOError if file is not readable
330 """
331 if not self.readable():
332 raise IOError("File or stream is not readable."
333 if msg is None else msg)
334
Guido van Rossum141f7672007-04-10 00:22:16 +0000335 def writable(self) -> bool:
336 """writable() -> bool. Return whether object was opened for writing.
337
338 If False, write() and truncate() will raise IOError.
339 """
340 return False
341
Guido van Rossum5abbf752007-08-27 17:39:33 +0000342 def _checkWritable(self, msg=None):
343 """Internal: raise an IOError if file is not writable
344 """
345 if not self.writable():
346 raise IOError("File or stream is not writable."
347 if msg is None else msg)
348
Guido van Rossum141f7672007-04-10 00:22:16 +0000349 @property
350 def closed(self):
351 """closed: bool. True iff the file has been closed.
352
353 For backwards compatibility, this is a property, not a predicate.
354 """
355 return self.__closed
356
Guido van Rossum5abbf752007-08-27 17:39:33 +0000357 def _checkClosed(self, msg=None):
358 """Internal: raise an ValueError if file is closed
359 """
360 if self.closed:
361 raise ValueError("I/O operation on closed file."
362 if msg is None else msg)
363
Guido van Rossum141f7672007-04-10 00:22:16 +0000364 ### Context manager ###
365
366 def __enter__(self) -> "IOBase": # That's a forward reference
367 """Context management protocol. Returns self."""
Christian Heimes3ecfea712008-02-09 20:51:34 +0000368 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000369 return self
370
371 def __exit__(self, *args) -> None:
372 """Context management protocol. Calls close()"""
373 self.close()
374
375 ### Lower-level APIs ###
376
377 # XXX Should these be present even if unimplemented?
378
379 def fileno(self) -> int:
380 """fileno() -> int. Returns underlying file descriptor if one exists.
381
382 Raises IOError if the IO object does not use a file descriptor.
383 """
384 self._unsupported("fileno")
385
386 def isatty(self) -> bool:
387 """isatty() -> int. Returns whether this is an 'interactive' stream.
388
389 Returns False if we don't know.
390 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000391 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000392 return False
393
Guido van Rossum7165cb12007-07-10 06:54:34 +0000394 ### Readline[s] and writelines ###
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000395
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000396 def readline(self, limit: int = -1) -> bytes:
397 """For backwards compatibility, a (slowish) readline()."""
Guido van Rossum2bf71382007-06-08 00:07:57 +0000398 if hasattr(self, "peek"):
399 def nreadahead():
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000400 readahead = self.peek(1)
Guido van Rossum2bf71382007-06-08 00:07:57 +0000401 if not readahead:
402 return 1
403 n = (readahead.find(b"\n") + 1) or len(readahead)
404 if limit >= 0:
405 n = min(n, limit)
406 return n
407 else:
408 def nreadahead():
409 return 1
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000410 if limit is None:
411 limit = -1
Guido van Rossum254348e2007-11-21 19:29:53 +0000412 res = bytearray()
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000413 while limit < 0 or len(res) < limit:
Guido van Rossum2bf71382007-06-08 00:07:57 +0000414 b = self.read(nreadahead())
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000415 if not b:
416 break
417 res += b
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000418 if res.endswith(b"\n"):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000419 break
Guido van Rossum98297ee2007-11-06 21:34:58 +0000420 return bytes(res)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000421
Guido van Rossum7165cb12007-07-10 06:54:34 +0000422 def __iter__(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000423 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000424 return self
425
426 def __next__(self):
427 line = self.readline()
428 if not line:
429 raise StopIteration
430 return line
431
432 def readlines(self, hint=None):
433 if hint is None:
434 return list(self)
435 n = 0
436 lines = []
437 for line in self:
438 lines.append(line)
439 n += len(line)
440 if n >= hint:
441 break
442 return lines
443
444 def writelines(self, lines):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000445 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000446 for line in lines:
447 self.write(line)
448
Guido van Rossum141f7672007-04-10 00:22:16 +0000449
450class RawIOBase(IOBase):
451
452 """Base class for raw binary I/O.
453
454 The read() method is implemented by calling readinto(); derived
455 classes that want to support read() only need to implement
456 readinto() as a primitive operation. In general, readinto()
457 can be more efficient than read().
458
459 (It would be tempting to also provide an implementation of
460 readinto() in terms of read(), in case the latter is a more
461 suitable primitive operation, but that would lead to nasty
462 recursion in case a subclass doesn't implement either.)
463 """
464
Guido van Rossum7165cb12007-07-10 06:54:34 +0000465 def read(self, n: int = -1) -> bytes:
Guido van Rossum78892e42007-04-06 17:31:18 +0000466 """read(n: int) -> bytes. Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000467
468 Returns an empty bytes array on EOF, or None if the object is
469 set not to block and has no data to read.
470 """
Guido van Rossum7165cb12007-07-10 06:54:34 +0000471 if n is None:
472 n = -1
473 if n < 0:
474 return self.readall()
Guido van Rossum254348e2007-11-21 19:29:53 +0000475 b = bytearray(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000476 n = self.readinto(b)
477 del b[n:]
Guido van Rossum98297ee2007-11-06 21:34:58 +0000478 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000479
Guido van Rossum7165cb12007-07-10 06:54:34 +0000480 def readall(self):
481 """readall() -> bytes. Read until EOF, using multiple read() call."""
Guido van Rossum254348e2007-11-21 19:29:53 +0000482 res = bytearray()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000483 while True:
484 data = self.read(DEFAULT_BUFFER_SIZE)
485 if not data:
486 break
487 res += data
Guido van Rossum98297ee2007-11-06 21:34:58 +0000488 return bytes(res)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000489
Guido van Rossum141f7672007-04-10 00:22:16 +0000490 def readinto(self, b: bytes) -> int:
491 """readinto(b: bytes) -> int. Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000492
493 Returns number of bytes read (0 for EOF), or None if the object
494 is set not to block as has no data to read.
495 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000496 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000497
Guido van Rossum141f7672007-04-10 00:22:16 +0000498 def write(self, b: bytes) -> int:
Guido van Rossum78892e42007-04-06 17:31:18 +0000499 """write(b: bytes) -> int. Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000500
Guido van Rossum78892e42007-04-06 17:31:18 +0000501 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000502 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000503 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000504
Guido van Rossum78892e42007-04-06 17:31:18 +0000505
Guido van Rossum141f7672007-04-10 00:22:16 +0000506class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000507
Guido van Rossum141f7672007-04-10 00:22:16 +0000508 """Raw I/O implementation for OS files.
Guido van Rossum28524c72007-02-27 05:47:44 +0000509
Guido van Rossum141f7672007-04-10 00:22:16 +0000510 This multiply inherits from _FileIO and RawIOBase to make
511 isinstance(io.FileIO(), io.RawIOBase) return True without
512 requiring that _fileio._FileIO inherits from io.RawIOBase (which
513 would be hard to do since _fileio.c is written in C).
514 """
Guido van Rossuma9e20242007-03-08 00:43:48 +0000515
Guido van Rossum87429772007-04-10 21:06:59 +0000516 def close(self):
517 _fileio._FileIO.close(self)
518 RawIOBase.close(self)
519
Guido van Rossum13633bb2007-04-13 18:42:35 +0000520 @property
521 def name(self):
522 return self._name
523
524 @property
525 def mode(self):
526 return self._mode
527
Guido van Rossuma9e20242007-03-08 00:43:48 +0000528
Guido van Rossumcce92b22007-04-10 14:41:39 +0000529class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000530
531 """Base class for buffered IO objects.
532
533 The main difference with RawIOBase is that the read() method
534 supports omitting the size argument, and does not have a default
535 implementation that defers to readinto().
536
537 In addition, read(), readinto() and write() may raise
538 BlockingIOError if the underlying raw stream is in non-blocking
539 mode and not ready; unlike their raw counterparts, they will never
540 return None.
541
542 A typical implementation should not inherit from a RawIOBase
543 implementation, but wrap one.
544 """
545
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000546 def read(self, n: int = None) -> bytes:
547 """read(n: int = None) -> bytes. Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000548
Guido van Rossum024da5c2007-05-17 23:59:11 +0000549 If the argument is omitted, None, or negative, reads and
550 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000551
552 If the argument is positive, and the underlying raw stream is
553 not 'interactive', multiple raw reads may be issued to satisfy
554 the byte count (unless EOF is reached first). But for
555 interactive raw streams (XXX and for pipes?), at most one raw
556 read will be issued, and a short result does not imply that
557 EOF is imminent.
558
559 Returns an empty bytes array on EOF.
560
561 Raises BlockingIOError if the underlying raw stream has no
562 data at the moment.
563 """
564 self._unsupported("read")
565
566 def readinto(self, b: bytes) -> int:
567 """readinto(b: bytes) -> int. Read up to len(b) bytes into b.
568
569 Like read(), this may issue multiple reads to the underlying
570 raw stream, unless the latter is 'interactive' (XXX or a
571 pipe?).
572
573 Returns the number of bytes read (0 for EOF).
574
575 Raises BlockingIOError if the underlying raw stream has no
576 data at the moment.
577 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000578 # XXX This ought to work with anything that supports the buffer API
Guido van Rossum87429772007-04-10 21:06:59 +0000579 data = self.read(len(b))
580 n = len(data)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000581 try:
582 b[:n] = data
583 except TypeError as err:
584 import array
585 if not isinstance(b, array.array):
586 raise err
587 b[:n] = array.array('b', data)
Guido van Rossum87429772007-04-10 21:06:59 +0000588 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000589
590 def write(self, b: bytes) -> int:
591 """write(b: bytes) -> int. Write the given buffer to the IO stream.
592
593 Returns the number of bytes written, which is never less than
594 len(b).
595
596 Raises BlockingIOError if the buffer is full and the
597 underlying raw stream cannot accept more data at the moment.
598 """
599 self._unsupported("write")
600
601
602class _BufferedIOMixin(BufferedIOBase):
603
604 """A mixin implementation of BufferedIOBase with an underlying raw stream.
605
606 This passes most requests on to the underlying raw stream. It
607 does *not* provide implementations of read(), readinto() or
608 write().
609 """
610
611 def __init__(self, raw):
612 self.raw = raw
613
614 ### Positioning ###
615
616 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000617 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000618
619 def tell(self):
620 return self.raw.tell()
621
622 def truncate(self, pos=None):
Guido van Rossum79b79ee2007-10-25 23:21:03 +0000623 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
624 # and a flush may be necessary to synch both views of the current
625 # file state.
626 self.flush()
Guido van Rossum57233cb2007-10-26 17:19:33 +0000627
628 if pos is None:
629 pos = self.tell()
630 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000631
632 ### Flush and close ###
633
634 def flush(self):
635 self.raw.flush()
636
637 def close(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000638 if not self.closed:
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000639 try:
640 self.flush()
641 except IOError:
642 pass # If flush() fails, just give up
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000643 self.raw.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000644
645 ### Inquiries ###
646
647 def seekable(self):
648 return self.raw.seekable()
649
650 def readable(self):
651 return self.raw.readable()
652
653 def writable(self):
654 return self.raw.writable()
655
656 @property
657 def closed(self):
658 return self.raw.closed
659
660 ### Lower-level APIs ###
661
662 def fileno(self):
663 return self.raw.fileno()
664
665 def isatty(self):
666 return self.raw.isatty()
667
668
Guido van Rossum024da5c2007-05-17 23:59:11 +0000669class BytesIO(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000670
Guido van Rossum024da5c2007-05-17 23:59:11 +0000671 """Buffered I/O implementation using an in-memory bytes buffer."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000672
Guido van Rossum024da5c2007-05-17 23:59:11 +0000673 # XXX More docs
674
675 def __init__(self, initial_bytes=None):
Guido van Rossum254348e2007-11-21 19:29:53 +0000676 buf = bytearray()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000677 if initial_bytes is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000678 buf += initial_bytes
679 self._buffer = buf
Guido van Rossum28524c72007-02-27 05:47:44 +0000680 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000681
682 def getvalue(self):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000683 return bytes(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000684
Guido van Rossum024da5c2007-05-17 23:59:11 +0000685 def read(self, n=None):
686 if n is None:
687 n = -1
Guido van Rossum141f7672007-04-10 00:22:16 +0000688 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000689 n = len(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000690 newpos = min(len(self._buffer), self._pos + n)
691 b = self._buffer[self._pos : newpos]
692 self._pos = newpos
Guido van Rossum98297ee2007-11-06 21:34:58 +0000693 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000694
Guido van Rossum024da5c2007-05-17 23:59:11 +0000695 def read1(self, n):
696 return self.read(n)
697
Guido van Rossum28524c72007-02-27 05:47:44 +0000698 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000699 if self.closed:
700 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +0000701 if isinstance(b, str):
702 raise TypeError("can't write str to binary stream")
Guido van Rossum28524c72007-02-27 05:47:44 +0000703 n = len(b)
704 newpos = self._pos + n
Guido van Rossumb972a782007-07-21 00:25:15 +0000705 if newpos > len(self._buffer):
706 # Inserts null bytes between the current end of the file
707 # and the new write position.
Guido van Rossuma74184e2007-08-29 04:05:57 +0000708 padding = b'\x00' * (newpos - len(self._buffer) - n)
Guido van Rossumb972a782007-07-21 00:25:15 +0000709 self._buffer[self._pos:newpos - n] = padding
Guido van Rossum28524c72007-02-27 05:47:44 +0000710 self._buffer[self._pos:newpos] = b
711 self._pos = newpos
712 return n
713
714 def seek(self, pos, whence=0):
Christian Heimes3ab4f652007-11-09 01:27:29 +0000715 try:
716 pos = pos.__index__()
717 except AttributeError as err:
718 raise TypeError("an integer is required") from err
Guido van Rossum28524c72007-02-27 05:47:44 +0000719 if whence == 0:
720 self._pos = max(0, pos)
721 elif whence == 1:
722 self._pos = max(0, self._pos + pos)
723 elif whence == 2:
724 self._pos = max(0, len(self._buffer) + pos)
725 else:
726 raise IOError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000727 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000728
729 def tell(self):
730 return self._pos
731
732 def truncate(self, pos=None):
733 if pos is None:
734 pos = self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000735 del self._buffer[pos:]
Guido van Rossum87429772007-04-10 21:06:59 +0000736 return pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000737
738 def readable(self):
739 return True
740
741 def writable(self):
742 return True
743
744 def seekable(self):
745 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000746
747
Guido van Rossum141f7672007-04-10 00:22:16 +0000748class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000749
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000750 """Buffer for a readable sequential RawIO object."""
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000751
Guido van Rossum78892e42007-04-06 17:31:18 +0000752 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000753 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000754 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000755 raw._checkReadable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000756 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum01a27522007-03-07 01:00:12 +0000757 self._read_buf = b""
Guido van Rossum78892e42007-04-06 17:31:18 +0000758 self.buffer_size = buffer_size
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000759
Guido van Rossum024da5c2007-05-17 23:59:11 +0000760 def read(self, n=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000761 """Read n bytes.
762
763 Returns exactly n bytes of data unless the underlying raw IO
Walter Dörwalda3270002007-05-29 19:13:29 +0000764 stream reaches EOF or if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000765 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000766 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000767 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000768 if n is None:
769 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +0000770 nodata_val = b""
Guido van Rossum141f7672007-04-10 00:22:16 +0000771 while n < 0 or len(self._read_buf) < n:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000772 to_read = max(self.buffer_size,
773 n if n is not None else 2*len(self._read_buf))
Guido van Rossum78892e42007-04-06 17:31:18 +0000774 current = self.raw.read(to_read)
Guido van Rossum78892e42007-04-06 17:31:18 +0000775 if current in (b"", None):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000776 nodata_val = current
777 break
Guido van Rossum01a27522007-03-07 01:00:12 +0000778 self._read_buf += current
779 if self._read_buf:
Guido van Rossum141f7672007-04-10 00:22:16 +0000780 if n < 0:
Guido van Rossum01a27522007-03-07 01:00:12 +0000781 n = len(self._read_buf)
782 out = self._read_buf[:n]
783 self._read_buf = self._read_buf[n:]
784 else:
785 out = nodata_val
786 return out
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000787
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000788 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000789 """Returns buffered bytes without advancing the position.
790
791 The argument indicates a desired minimal number of bytes; we
792 do at most one raw read to satisfy it. We never return more
793 than self.buffer_size.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000794 """
795 want = min(n, self.buffer_size)
796 have = len(self._read_buf)
797 if have < want:
798 to_read = self.buffer_size - have
799 current = self.raw.read(to_read)
800 if current:
801 self._read_buf += current
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000802 return self._read_buf
Guido van Rossum13633bb2007-04-13 18:42:35 +0000803
804 def read1(self, n):
805 """Reads up to n bytes.
806
807 Returns up to n bytes. If at least one byte is buffered,
808 we only return buffered bytes. Otherwise, we do one
809 raw read.
810 """
811 if n <= 0:
812 return b""
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000813 self.peek(1)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000814 return self.read(min(n, len(self._read_buf)))
815
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000816 def tell(self):
817 return self.raw.tell() - len(self._read_buf)
818
819 def seek(self, pos, whence=0):
820 if whence == 1:
821 pos -= len(self._read_buf)
Guido van Rossum53807da2007-04-10 19:01:47 +0000822 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000823 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +0000824 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000825
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000826
Guido van Rossum141f7672007-04-10 00:22:16 +0000827class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000828
Guido van Rossum78892e42007-04-06 17:31:18 +0000829 # XXX docstring
830
Guido van Rossum141f7672007-04-10 00:22:16 +0000831 def __init__(self, raw,
832 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000833 raw._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000834 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000835 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +0000836 self.max_buffer_size = (2*buffer_size
837 if max_buffer_size is None
838 else max_buffer_size)
Guido van Rossum254348e2007-11-21 19:29:53 +0000839 self._write_buf = bytearray()
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000840
841 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000842 if self.closed:
843 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +0000844 if isinstance(b, str):
845 raise TypeError("can't write str to binary stream")
Guido van Rossum01a27522007-03-07 01:00:12 +0000846 # XXX we can implement some more tricks to try and avoid partial writes
Guido van Rossum01a27522007-03-07 01:00:12 +0000847 if len(self._write_buf) > self.buffer_size:
848 # We're full, so let's pre-flush the buffer
849 try:
850 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000851 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000852 # We can't accept anything else.
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000853 # XXX Why not just let the exception pass through?
Guido van Rossum141f7672007-04-10 00:22:16 +0000854 raise BlockingIOError(e.errno, e.strerror, 0)
Guido van Rossumd4103952007-04-12 05:44:49 +0000855 before = len(self._write_buf)
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000856 self._write_buf.extend(b)
Guido van Rossumd4103952007-04-12 05:44:49 +0000857 written = len(self._write_buf) - before
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000858 if len(self._write_buf) > self.buffer_size:
Guido van Rossum01a27522007-03-07 01:00:12 +0000859 try:
860 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000861 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000862 if (len(self._write_buf) > self.max_buffer_size):
863 # We've hit max_buffer_size. We have to accept a partial
864 # write and cut back our buffer.
865 overage = len(self._write_buf) - self.max_buffer_size
866 self._write_buf = self._write_buf[:self.max_buffer_size]
Guido van Rossum141f7672007-04-10 00:22:16 +0000867 raise BlockingIOError(e.errno, e.strerror, overage)
Guido van Rossumd4103952007-04-12 05:44:49 +0000868 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000869
870 def flush(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000871 if self.closed:
872 raise ValueError("flush of closed file")
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000873 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +0000874 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000875 while self._write_buf:
876 n = self.raw.write(self._write_buf)
877 del self._write_buf[:n]
878 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000879 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000880 n = e.characters_written
881 del self._write_buf[:n]
882 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000883 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000884
885 def tell(self):
886 return self.raw.tell() + len(self._write_buf)
887
888 def seek(self, pos, whence=0):
889 self.flush()
Guido van Rossum53807da2007-04-10 19:01:47 +0000890 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000891
Guido van Rossum01a27522007-03-07 01:00:12 +0000892
Guido van Rossum141f7672007-04-10 00:22:16 +0000893class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000894
Guido van Rossum01a27522007-03-07 01:00:12 +0000895 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000896
Guido van Rossum141f7672007-04-10 00:22:16 +0000897 A buffered reader object and buffered writer object put together
898 to form a sequential IO object that can read and write.
Guido van Rossum78892e42007-04-06 17:31:18 +0000899
900 This is typically used with a socket or two-way pipe.
Guido van Rossum141f7672007-04-10 00:22:16 +0000901
902 XXX The usefulness of this (compared to having two separate IO
903 objects) is questionable.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000904 """
905
Guido van Rossum141f7672007-04-10 00:22:16 +0000906 def __init__(self, reader, writer,
907 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
908 """Constructor.
909
910 The arguments are two RawIO instances.
911 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000912 reader._checkReadable()
913 writer._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000914 self.reader = BufferedReader(reader, buffer_size)
915 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +0000916
Guido van Rossum024da5c2007-05-17 23:59:11 +0000917 def read(self, n=None):
918 if n is None:
919 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +0000920 return self.reader.read(n)
921
Guido van Rossum141f7672007-04-10 00:22:16 +0000922 def readinto(self, b):
923 return self.reader.readinto(b)
924
Guido van Rossum01a27522007-03-07 01:00:12 +0000925 def write(self, b):
926 return self.writer.write(b)
927
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000928 def peek(self, n=0):
929 return self.reader.peek(n)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000930
931 def read1(self, n):
932 return self.reader.read1(n)
933
Guido van Rossum01a27522007-03-07 01:00:12 +0000934 def readable(self):
935 return self.reader.readable()
936
937 def writable(self):
938 return self.writer.writable()
939
940 def flush(self):
941 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000942
Guido van Rossum01a27522007-03-07 01:00:12 +0000943 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +0000944 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000945 self.reader.close()
946
947 def isatty(self):
948 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +0000949
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000950 @property
951 def closed(self):
Guido van Rossum141f7672007-04-10 00:22:16 +0000952 return self.writer.closed()
Guido van Rossum01a27522007-03-07 01:00:12 +0000953
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000954
Guido van Rossum141f7672007-04-10 00:22:16 +0000955class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +0000956
Guido van Rossum78892e42007-04-06 17:31:18 +0000957 # XXX docstring
958
Guido van Rossum141f7672007-04-10 00:22:16 +0000959 def __init__(self, raw,
960 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000961 raw._checkSeekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000962 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +0000963 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
964
Guido van Rossum01a27522007-03-07 01:00:12 +0000965 def seek(self, pos, whence=0):
966 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000967 # First do the raw seek, then empty the read buffer, so that
968 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +0000969 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000970 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +0000971 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +0000972
973 def tell(self):
974 if (self._write_buf):
975 return self.raw.tell() + len(self._write_buf)
976 else:
977 return self.raw.tell() - len(self._read_buf)
978
Guido van Rossum024da5c2007-05-17 23:59:11 +0000979 def read(self, n=None):
980 if n is None:
981 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +0000982 self.flush()
983 return BufferedReader.read(self, n)
984
Guido van Rossum141f7672007-04-10 00:22:16 +0000985 def readinto(self, b):
986 self.flush()
987 return BufferedReader.readinto(self, b)
988
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000989 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000990 self.flush()
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000991 return BufferedReader.peek(self, n)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000992
993 def read1(self, n):
994 self.flush()
995 return BufferedReader.read1(self, n)
996
Guido van Rossum01a27522007-03-07 01:00:12 +0000997 def write(self, b):
Guido van Rossum78892e42007-04-06 17:31:18 +0000998 if self._read_buf:
999 self.raw.seek(-len(self._read_buf), 1) # Undo readahead
1000 self._read_buf = b""
Guido van Rossum01a27522007-03-07 01:00:12 +00001001 return BufferedWriter.write(self, b)
1002
Guido van Rossum78892e42007-04-06 17:31:18 +00001003
Guido van Rossumcce92b22007-04-10 14:41:39 +00001004class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +00001005
1006 """Base class for text I/O.
1007
1008 This class provides a character and line based interface to stream I/O.
Guido van Rossum9b76da62007-04-11 01:09:03 +00001009
1010 There is no readinto() method, as character strings are immutable.
Guido van Rossum78892e42007-04-06 17:31:18 +00001011 """
1012
1013 def read(self, n: int = -1) -> str:
1014 """read(n: int = -1) -> str. Read at most n characters from stream.
1015
1016 Read from underlying buffer until we have n characters or we hit EOF.
1017 If n is negative or omitted, read until EOF.
1018 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001019 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +00001020
Guido van Rossum9b76da62007-04-11 01:09:03 +00001021 def write(self, s: str) -> int:
1022 """write(s: str) -> int. Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001023 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +00001024
Guido van Rossum9b76da62007-04-11 01:09:03 +00001025 def truncate(self, pos: int = None) -> int:
1026 """truncate(pos: int = None) -> int. Truncate size to pos."""
1027 self.flush()
1028 if pos is None:
1029 pos = self.tell()
1030 self.seek(pos)
1031 return self.buffer.truncate()
1032
Guido van Rossum78892e42007-04-06 17:31:18 +00001033 def readline(self) -> str:
1034 """readline() -> str. Read until newline or EOF.
1035
1036 Returns an empty string if EOF is hit immediately.
1037 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001038 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +00001039
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001040 @property
1041 def encoding(self):
1042 """Subclasses should override."""
1043 return None
1044
Guido van Rossum8358db22007-08-18 21:39:55 +00001045 @property
1046 def newlines(self):
1047 """newlines -> None | str | tuple of str. Line endings translated
1048 so far.
1049
1050 Only line endings translated during reading are considered.
1051
1052 Subclasses should override.
1053 """
1054 return None
1055
Guido van Rossum78892e42007-04-06 17:31:18 +00001056
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001057class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1058 """Codec used when reading a file in universal newlines mode.
1059 It wraps another incremental decoder, translating \\r\\n and \\r into \\n.
1060 It also records the types of newlines encountered.
1061 When used with translate=False, it ensures that the newline sequence is
1062 returned in one piece.
1063 """
1064 def __init__(self, decoder, translate, errors='strict'):
1065 codecs.IncrementalDecoder.__init__(self, errors=errors)
1066 self.buffer = b''
1067 self.translate = translate
1068 self.decoder = decoder
1069 self.seennl = 0
1070
1071 def decode(self, input, final=False):
1072 # decode input (with the eventual \r from a previous pass)
1073 if self.buffer:
1074 input = self.buffer + input
1075
1076 output = self.decoder.decode(input, final=final)
1077
1078 # retain last \r even when not translating data:
1079 # then readline() is sure to get \r\n in one pass
1080 if output.endswith("\r") and not final:
1081 output = output[:-1]
1082 self.buffer = b'\r'
1083 else:
1084 self.buffer = b''
1085
1086 # Record which newlines are read
1087 crlf = output.count('\r\n')
1088 cr = output.count('\r') - crlf
1089 lf = output.count('\n') - crlf
1090 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1091 | (crlf and self._CRLF)
1092
1093 if self.translate:
1094 if crlf:
1095 output = output.replace("\r\n", "\n")
1096 if cr:
1097 output = output.replace("\r", "\n")
1098
1099 return output
1100
1101 def getstate(self):
1102 buf, flag = self.decoder.getstate()
1103 return buf + self.buffer, flag
1104
1105 def setstate(self, state):
1106 buf, flag = state
1107 if buf.endswith(b'\r'):
1108 self.buffer = b'\r'
1109 buf = buf[:-1]
1110 else:
1111 self.buffer = b''
1112 self.decoder.setstate((buf, flag))
1113
1114 def reset(self):
Alexandre Vassalottic3d7fe02007-12-28 01:24:22 +00001115 self.seennl = 0
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001116 self.buffer = b''
1117 self.decoder.reset()
1118
1119 _LF = 1
1120 _CR = 2
1121 _CRLF = 4
1122
1123 @property
1124 def newlines(self):
1125 return (None,
1126 "\n",
1127 "\r",
1128 ("\r", "\n"),
1129 "\r\n",
1130 ("\n", "\r\n"),
1131 ("\r", "\r\n"),
1132 ("\r", "\n", "\r\n")
1133 )[self.seennl]
1134
1135
Guido van Rossum78892e42007-04-06 17:31:18 +00001136class TextIOWrapper(TextIOBase):
1137
1138 """Buffered text stream.
1139
1140 Character and line based layer over a BufferedIOBase object.
1141 """
1142
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001143 _CHUNK_SIZE = 128
Guido van Rossum78892e42007-04-06 17:31:18 +00001144
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001145 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1146 line_buffering=False):
Guido van Rossum8358db22007-08-18 21:39:55 +00001147 if newline not in (None, "", "\n", "\r", "\r\n"):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001148 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +00001149 if encoding is None:
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001150 try:
1151 encoding = os.device_encoding(buffer.fileno())
Brett Cannon041683d2007-10-11 23:08:53 +00001152 except (AttributeError, UnsupportedOperation):
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001153 pass
1154 if encoding is None:
Martin v. Löwisd78d3b42007-08-11 15:36:45 +00001155 try:
1156 import locale
1157 except ImportError:
1158 # Importing locale may fail if Python is being built
1159 encoding = "ascii"
1160 else:
1161 encoding = locale.getpreferredencoding()
Guido van Rossum78892e42007-04-06 17:31:18 +00001162
Christian Heimes8bd14fb2007-11-08 16:34:32 +00001163 if not isinstance(encoding, str):
1164 raise ValueError("invalid encoding: %r" % encoding)
1165
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001166 if errors is None:
1167 errors = "strict"
1168 else:
1169 if not isinstance(errors, str):
1170 raise ValueError("invalid errors: %r" % errors)
1171
Guido van Rossum78892e42007-04-06 17:31:18 +00001172 self.buffer = buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001173 self._line_buffering = line_buffering
Guido van Rossum78892e42007-04-06 17:31:18 +00001174 self._encoding = encoding
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001175 self._errors = errors
Guido van Rossum8358db22007-08-18 21:39:55 +00001176 self._readuniversal = not newline
1177 self._readtranslate = newline is None
1178 self._readnl = newline
1179 self._writetranslate = newline != ''
1180 self._writenl = newline or os.linesep
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001181 self._encoder = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001182 self._decoder = None
Guido van Rossum9b76da62007-04-11 01:09:03 +00001183 self._pending = ""
1184 self._snapshot = None
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001185 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001186
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001187 @property
1188 def encoding(self):
1189 return self._encoding
1190
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001191 @property
1192 def errors(self):
1193 return self._errors
1194
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001195 @property
1196 def line_buffering(self):
1197 return self._line_buffering
1198
Guido van Rossum9b76da62007-04-11 01:09:03 +00001199 # A word about _snapshot. This attribute is either None, or a
Guido van Rossumd76e7792007-04-17 02:38:04 +00001200 # tuple (decoder_state, readahead, pending) where decoder_state is
1201 # the second (integer) item of the decoder state, readahead is the
1202 # chunk of bytes that was read, and pending is the characters that
1203 # were rendered by the decoder after feeding it those bytes. We
1204 # use this to reconstruct intermediate decoder states in tell().
Guido van Rossum9b76da62007-04-11 01:09:03 +00001205
Ka-Ping Yeeddaa7062008-03-17 20:35:15 +00001206 def seekable(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001207 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +00001208
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001209 def flush(self):
1210 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001211 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001212
1213 def close(self):
Guido van Rossum33e7a8e2007-07-22 20:38:07 +00001214 try:
1215 self.flush()
1216 except:
1217 pass # If flush() fails, just give up
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001218 self.buffer.close()
1219
1220 @property
1221 def closed(self):
1222 return self.buffer.closed
1223
Guido van Rossum9be55972007-04-07 02:59:27 +00001224 def fileno(self):
1225 return self.buffer.fileno()
1226
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001227 def isatty(self):
1228 return self.buffer.isatty()
1229
Guido van Rossum78892e42007-04-06 17:31:18 +00001230 def write(self, s: str):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001231 if self.closed:
1232 raise ValueError("write to closed file")
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001233 if not isinstance(s, str):
Guido van Rossumdcce8392007-08-29 18:10:08 +00001234 raise TypeError("can't write %s to text stream" %
1235 s.__class__.__name__)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001236 length = len(s)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001237 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
Guido van Rossum8358db22007-08-18 21:39:55 +00001238 if haslf and self._writetranslate and self._writenl != "\n":
1239 s = s.replace("\n", self._writenl)
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001240 encoder = self._encoder or self._get_encoder()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001241 # XXX What if we were just reading?
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001242 b = encoder.encode(s)
Guido van Rossum8358db22007-08-18 21:39:55 +00001243 self.buffer.write(b)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001244 if self._line_buffering and (haslf or "\r" in s):
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001245 self.flush()
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001246 self._snapshot = None
1247 if self._decoder:
1248 self._decoder.reset()
1249 return length
Guido van Rossum78892e42007-04-06 17:31:18 +00001250
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001251 def _get_encoder(self):
1252 make_encoder = codecs.getincrementalencoder(self._encoding)
1253 self._encoder = make_encoder(self._errors)
1254 return self._encoder
1255
Guido van Rossum78892e42007-04-06 17:31:18 +00001256 def _get_decoder(self):
1257 make_decoder = codecs.getincrementaldecoder(self._encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001258 decoder = make_decoder(self._errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001259 if self._readuniversal:
1260 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1261 self._decoder = decoder
Guido van Rossum78892e42007-04-06 17:31:18 +00001262 return decoder
1263
Guido van Rossum9b76da62007-04-11 01:09:03 +00001264 def _read_chunk(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001265 if self._decoder is None:
1266 raise ValueError("no decoder")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001267 if not self._telling:
Guido van Rossum13633bb2007-04-13 18:42:35 +00001268 readahead = self.buffer.read1(self._CHUNK_SIZE)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001269 pending = self._decoder.decode(readahead, not readahead)
1270 return readahead, pending
Guido van Rossumd76e7792007-04-17 02:38:04 +00001271 decoder_buffer, decoder_state = self._decoder.getstate()
Guido van Rossum13633bb2007-04-13 18:42:35 +00001272 readahead = self.buffer.read1(self._CHUNK_SIZE)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001273 pending = self._decoder.decode(readahead, not readahead)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001274 self._snapshot = (decoder_state, decoder_buffer + readahead, pending)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001275 return readahead, pending
Guido van Rossum9b76da62007-04-11 01:09:03 +00001276
1277 def _encode_decoder_state(self, ds, pos):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001278 x = 0
1279 for i in bytes(ds):
1280 x = x<<8 | i
1281 return (x<<64) | pos
1282
1283 def _decode_decoder_state(self, pos):
1284 x, pos = divmod(pos, 1<<64)
1285 if not x:
1286 return None, pos
1287 b = b""
1288 while x:
1289 b.append(x&0xff)
1290 x >>= 8
1291 return str(b[::-1]), pos
1292
1293 def tell(self):
1294 if not self._seekable:
1295 raise IOError("Underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001296 if not self._telling:
1297 raise IOError("Telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001298 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001299 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001300 decoder = self._decoder
1301 if decoder is None or self._snapshot is None:
Guido van Rossum5abbf752007-08-27 17:39:33 +00001302 if self._pending:
1303 raise ValueError("pending data")
Guido van Rossumcba608c2007-04-11 14:19:59 +00001304 return position
1305 decoder_state, readahead, pending = self._snapshot
1306 position -= len(readahead)
1307 needed = len(pending) - len(self._pending)
1308 if not needed:
1309 return self._encode_decoder_state(decoder_state, position)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001310 saved_state = decoder.getstate()
1311 try:
Guido van Rossum2b08b382007-05-08 20:18:39 +00001312 decoder.setstate((b"", decoder_state))
Guido van Rossumd76e7792007-04-17 02:38:04 +00001313 n = 0
Guido van Rossum254348e2007-11-21 19:29:53 +00001314 bb = bytearray(1)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001315 for i, bb[0] in enumerate(readahead):
1316 n += len(decoder.decode(bb))
1317 if n >= needed:
1318 decoder_buffer, decoder_state = decoder.getstate()
1319 return self._encode_decoder_state(
1320 decoder_state,
Amaury Forgeot d'Arca2d1d7e2007-11-19 21:14:47 +00001321 position + (i+1) - len(decoder_buffer) - (n - needed))
Guido van Rossumd76e7792007-04-17 02:38:04 +00001322 raise IOError("Can't reconstruct logical file position")
1323 finally:
1324 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001325
1326 def seek(self, pos, whence=0):
1327 if not self._seekable:
1328 raise IOError("Underlying stream is not seekable")
1329 if whence == 1:
1330 if pos != 0:
1331 raise IOError("Can't do nonzero cur-relative seeks")
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001332 pos = self.tell()
1333 whence = 0
Guido van Rossum9b76da62007-04-11 01:09:03 +00001334 if whence == 2:
1335 if pos != 0:
1336 raise IOError("Can't do nonzero end-relative seeks")
1337 self.flush()
1338 pos = self.buffer.seek(0, 2)
1339 self._snapshot = None
1340 self._pending = ""
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001341 if self._decoder:
1342 self._decoder.reset()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001343 return pos
1344 if whence != 0:
1345 raise ValueError("Invalid whence (%r, should be 0, 1 or 2)" %
1346 (whence,))
1347 if pos < 0:
1348 raise ValueError("Negative seek position %r" % (pos,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001349 self.flush()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001350 orig_pos = pos
1351 ds, pos = self._decode_decoder_state(pos)
1352 if not ds:
1353 self.buffer.seek(pos)
1354 self._snapshot = None
1355 self._pending = ""
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001356 if self._decoder:
1357 self._decoder.reset()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001358 return pos
Guido van Rossumd76e7792007-04-17 02:38:04 +00001359 decoder = self._decoder or self._get_decoder()
1360 decoder.set_state(("", ds))
Guido van Rossum9b76da62007-04-11 01:09:03 +00001361 self.buffer.seek(pos)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001362 self._snapshot = (ds, b"", "")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001363 self._pending = ""
Guido van Rossumcba608c2007-04-11 14:19:59 +00001364 self._decoder = decoder
Guido van Rossum9b76da62007-04-11 01:09:03 +00001365 return orig_pos
1366
Guido van Rossum024da5c2007-05-17 23:59:11 +00001367 def read(self, n=None):
1368 if n is None:
1369 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001370 decoder = self._decoder or self._get_decoder()
1371 res = self._pending
1372 if n < 0:
1373 res += decoder.decode(self.buffer.read(), True)
Guido van Rossum141f7672007-04-10 00:22:16 +00001374 self._pending = ""
Guido van Rossum9b76da62007-04-11 01:09:03 +00001375 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001376 return res
Guido van Rossum78892e42007-04-06 17:31:18 +00001377 else:
1378 while len(res) < n:
Guido van Rossumcba608c2007-04-11 14:19:59 +00001379 readahead, pending = self._read_chunk()
1380 res += pending
1381 if not readahead:
Guido van Rossum78892e42007-04-06 17:31:18 +00001382 break
1383 self._pending = res[n:]
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001384 return res[:n]
Guido van Rossum78892e42007-04-06 17:31:18 +00001385
Guido van Rossum024da5c2007-05-17 23:59:11 +00001386 def __next__(self):
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001387 self._telling = False
1388 line = self.readline()
1389 if not line:
1390 self._snapshot = None
1391 self._telling = self._seekable
1392 raise StopIteration
1393 return line
1394
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001395 def readline(self, limit=None):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001396 if limit is None:
1397 limit = -1
1398 if limit >= 0:
Guido van Rossum9b76da62007-04-11 01:09:03 +00001399 # XXX Hack to support limit argument, for backwards compatibility
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001400 line = self.readline()
1401 if len(line) <= limit:
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001402 return line
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001403 line, self._pending = line[:limit], line[limit:] + self._pending
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001404 return line
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001405
Guido van Rossum78892e42007-04-06 17:31:18 +00001406 line = self._pending
1407 start = 0
1408 decoder = self._decoder or self._get_decoder()
1409
Guido van Rossum8358db22007-08-18 21:39:55 +00001410 pos = endpos = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001411 while True:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001412 if self._readtranslate:
1413 # Newlines are already translated, only search for \n
1414 pos = line.find('\n', start)
1415 if pos >= 0:
1416 endpos = pos + 1
1417 break
1418 else:
1419 start = len(line)
1420
1421 elif self._readuniversal:
Guido van Rossum8358db22007-08-18 21:39:55 +00001422 # Universal newline search. Find any of \r, \r\n, \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001423 # The decoder ensures that \r\n are not split in two pieces
Guido van Rossum78892e42007-04-06 17:31:18 +00001424
Guido van Rossum8358db22007-08-18 21:39:55 +00001425 # In C we'd look for these in parallel of course.
1426 nlpos = line.find("\n", start)
1427 crpos = line.find("\r", start)
1428 if crpos == -1:
1429 if nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001430 # Nothing found
Guido van Rossum8358db22007-08-18 21:39:55 +00001431 start = len(line)
Guido van Rossum78892e42007-04-06 17:31:18 +00001432 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001433 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001434 endpos = nlpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001435 break
1436 elif nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001437 # Found lone \r
1438 endpos = crpos + 1
1439 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001440 elif nlpos < crpos:
1441 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001442 endpos = nlpos + 1
Guido van Rossum78892e42007-04-06 17:31:18 +00001443 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001444 elif nlpos == crpos + 1:
1445 # Found \r\n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001446 endpos = crpos + 2
Guido van Rossum8358db22007-08-18 21:39:55 +00001447 break
1448 else:
1449 # Found \r
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001450 endpos = crpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001451 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001452 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001453 # non-universal
1454 pos = line.find(self._readnl)
1455 if pos >= 0:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001456 endpos = pos + len(self._readnl)
Guido van Rossum8358db22007-08-18 21:39:55 +00001457 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001458
1459 # No line ending seen yet - get more data
Guido van Rossum8358db22007-08-18 21:39:55 +00001460 more_line = ''
Guido van Rossum78892e42007-04-06 17:31:18 +00001461 while True:
Guido van Rossumcba608c2007-04-11 14:19:59 +00001462 readahead, pending = self._read_chunk()
1463 more_line = pending
1464 if more_line or not readahead:
Guido van Rossum78892e42007-04-06 17:31:18 +00001465 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001466 if more_line:
1467 line += more_line
1468 else:
1469 # end of file
1470 self._pending = ''
1471 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001472 return line
Guido van Rossum78892e42007-04-06 17:31:18 +00001473
Guido van Rossum8358db22007-08-18 21:39:55 +00001474 self._pending = line[endpos:]
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001475 return line[:endpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001476
Guido van Rossum8358db22007-08-18 21:39:55 +00001477 @property
1478 def newlines(self):
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001479 return self._decoder.newlines if self._decoder else None
Guido van Rossum024da5c2007-05-17 23:59:11 +00001480
1481class StringIO(TextIOWrapper):
1482
1483 # XXX This is really slow, but fully functional
1484
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001485 def __init__(self, initial_value="", encoding="utf-8",
1486 errors="strict", newline="\n"):
Guido van Rossum3e1f85e2007-07-27 18:03:11 +00001487 super(StringIO, self).__init__(BytesIO(),
1488 encoding=encoding,
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001489 errors=errors,
Guido van Rossum3e1f85e2007-07-27 18:03:11 +00001490 newline=newline)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001491 if initial_value:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001492 if not isinstance(initial_value, str):
Guido van Rossum34d19282007-08-09 01:03:29 +00001493 initial_value = str(initial_value)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001494 self.write(initial_value)
1495 self.seek(0)
1496
1497 def getvalue(self):
Guido van Rossum34d19282007-08-09 01:03:29 +00001498 self.flush()
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001499 return self.buffer.getvalue().decode(self._encoding, self._errors)