blob: 18680cad534758bc36870135c949bb8075338ec8 [file] [log] [blame]
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +00001"""The io module provides the Python interfaces to stream handling. The
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00002builtin open function is defined in this module.
3
4At the top of the I/O hierarchy is the abstract base class IOBase. It
5defines the basic interface to a stream. Note, however, that there is no
6seperation between reading and writing to streams; implementations are
7allowed to throw an IOError if they do not support a given operation.
8
9Extending IOBase is RawIOBase which deals simply with the reading and
10writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
11an interface to OS files.
12
13BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
14subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
15streams that are readable, writable, and both respectively.
16BufferedRandom provides a buffered interface to random access
17streams. BytesIO is a simple stream of in-memory bytes.
18
19Another IOBase subclass, TextIOBase, deals with the encoding and decoding
20of streams into text. TextIOWrapper, which extends it, is a buffered text
21interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
22is a in-memory stream for text.
23
24Argument names are not part of the specification, and only the arguments
25of open() are intended to be used as keyword arguments.
26
27data:
28
29DEFAULT_BUFFER_SIZE
30
31 An int containing the default buffer size used by the module's buffered
32 I/O classes. open() uses the file's blksize (as obtained by os.stat) if
33 possible.
34"""
35# New I/O library conforming to PEP 3116.
36
37# This is a prototype; hopefully eventually some of this will be
38# reimplemented in C.
39
40# XXX edge cases when switching between reading/writing
41# XXX need to support 1 meaning line-buffered
42# XXX whenever an argument is None, use the default value
43# XXX read/write ops should check readable/writable
44# XXX buffered readinto should work with arbitrary buffer objects
45# XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG
46# XXX check writable, readable and seekable in appropriate places
47
Guido van Rossum28524c72007-02-27 05:47:44 +000048
Guido van Rossum68bbcd22007-02-27 17:19:33 +000049__author__ = ("Guido van Rossum <guido@python.org>, "
Guido van Rossum78892e42007-04-06 17:31:18 +000050 "Mike Verdone <mike.verdone@gmail.com>, "
51 "Mark Russell <mark.russell@zen.co.uk>")
Guido van Rossum28524c72007-02-27 05:47:44 +000052
Guido van Rossum141f7672007-04-10 00:22:16 +000053__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
Guido van Rossum5abbf752007-08-27 17:39:33 +000054 "BytesIO", "StringIO", "BufferedIOBase",
Guido van Rossum01a27522007-03-07 01:00:12 +000055 "BufferedReader", "BufferedWriter", "BufferedRWPair",
Guido van Rossum141f7672007-04-10 00:22:16 +000056 "BufferedRandom", "TextIOBase", "TextIOWrapper"]
Guido van Rossum28524c72007-02-27 05:47:44 +000057
58import os
Guido van Rossumb7f136e2007-08-22 18:14:10 +000059import abc
Guido van Rossum78892e42007-04-06 17:31:18 +000060import sys
61import codecs
Guido van Rossum141f7672007-04-10 00:22:16 +000062import _fileio
Guido van Rossum78892e42007-04-06 17:31:18 +000063import warnings
Antoine Pitroue1e48ea2008-08-15 00:05:08 +000064from _thread import allocate_lock as Lock
Guido van Rossum28524c72007-02-27 05:47:44 +000065
Guido van Rossum5abbf752007-08-27 17:39:33 +000066# open() uses st_blksize whenever we can
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000067DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
Guido van Rossum01a27522007-03-07 01:00:12 +000068
69
Guido van Rossum141f7672007-04-10 00:22:16 +000070class BlockingIOError(IOError):
Guido van Rossum78892e42007-04-06 17:31:18 +000071
Guido van Rossum141f7672007-04-10 00:22:16 +000072 """Exception raised when I/O would block on a non-blocking I/O stream."""
73
74 def __init__(self, errno, strerror, characters_written=0):
Guido van Rossum01a27522007-03-07 01:00:12 +000075 IOError.__init__(self, errno, strerror)
76 self.characters_written = characters_written
77
Guido van Rossum68bbcd22007-02-27 17:19:33 +000078
Guido van Rossume7fc50f2007-12-03 22:54:21 +000079def open(file, mode="r", buffering=None, encoding=None, errors=None,
80 newline=None, closefd=True):
Christian Heimes5d8da202008-05-06 13:58:24 +000081
82 r"""Open file and return a stream. If the file cannot be opened, an IOError is
83 raised.
Guido van Rossum17e43e52007-02-27 15:45:13 +000084
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000085 file is either a string giving the name (and the path if the file
86 isn't in the current working directory) of the file to be opened or an
87 integer file descriptor of the file to be wrapped. (If a file
88 descriptor is given, it is closed when the returned I/O object is
89 closed, unless closefd is set to False.)
Guido van Rossum8358db22007-08-18 21:39:55 +000090
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000091 mode is an optional string that specifies the mode in which the file
92 is opened. It defaults to 'r' which means open for reading in text
93 mode. Other common values are 'w' for writing (truncating the file if
94 it already exists), and 'a' for appending (which on some Unix systems,
95 means that all writes append to the end of the file regardless of the
96 current seek position). In text mode, if encoding is not specified the
97 encoding used is platform dependent. (For reading and writing raw
98 bytes use binary mode and leave encoding unspecified.) The available
99 modes are:
Guido van Rossum8358db22007-08-18 21:39:55 +0000100
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000101 ========= ===============================================================
102 Character Meaning
103 --------- ---------------------------------------------------------------
104 'r' open for reading (default)
105 'w' open for writing, truncating the file first
106 'a' open for writing, appending to the end of the file if it exists
107 'b' binary mode
108 't' text mode (default)
109 '+' open a disk file for updating (reading and writing)
110 'U' universal newline mode (for backwards compatibility; unneeded
111 for new code)
112 ========= ===============================================================
Guido van Rossum17e43e52007-02-27 15:45:13 +0000113
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000114 The default mode is 'rt' (open for reading text). For binary random
115 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
116 'r+b' opens the file without truncation.
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000117
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000118 Python distinguishes between files opened in binary and text modes,
119 even when the underlying operating system doesn't. Files opened in
120 binary mode (appending 'b' to the mode argument) return contents as
121 bytes objects without any decoding. In text mode (the default, or when
122 't' is appended to the mode argument), the contents of the file are
123 returned as strings, the bytes having been first decoded using a
124 platform-dependent encoding or using the specified encoding if given.
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000125
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000126 buffering is an optional integer used to set the buffering policy. By
127 default full buffering is on. Pass 0 to switch buffering off (only
128 allowed in binary mode), 1 to set line buffering, and an integer > 1
129 for full buffering.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000130
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000131 encoding is the name of the encoding used to decode or encode the
132 file. This should only be used in text mode. The default encoding is
133 platform dependent, but any encoding supported by Python can be
134 passed. See the codecs module for the list of supported encodings.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000135
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000136 errors is an optional string that specifies how encoding errors are to
137 be handled---this argument should not be used in binary mode. Pass
138 'strict' to raise a ValueError exception if there is an encoding error
139 (the default of None has the same effect), or pass 'ignore' to ignore
140 errors. (Note that ignoring encoding errors can lead to data loss.)
141 See the documentation for codecs.register for a list of the permitted
142 encoding error strings.
143
144 newline controls how universal newlines works (it only applies to text
145 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
146 follows:
147
148 * On input, if newline is None, universal newlines mode is
149 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
150 these are translated into '\n' before being returned to the
151 caller. If it is '', universal newline mode is enabled, but line
152 endings are returned to the caller untranslated. If it has any of
153 the other legal values, input lines are only terminated by the given
154 string, and the line ending is returned to the caller untranslated.
155
156 * On output, if newline is None, any '\n' characters written are
157 translated to the system default line separator, os.linesep. If
158 newline is '', no translation takes place. If newline is any of the
159 other legal values, any '\n' characters written are translated to
160 the given string.
161
162 If closefd is False, the underlying file descriptor will be kept open
163 when the file is closed. This does not work when a file name is given
164 and must be True in that case.
165
166 open() returns a file object whose type depends on the mode, and
167 through which the standard file operations such as reading and writing
168 are performed. When open() is used to open a file in a text mode ('w',
169 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
170 a file in a binary mode, the returned class varies: in read binary
171 mode, it returns a BufferedReader; in write binary and append binary
172 modes, it returns a BufferedWriter, and in read/write mode, it returns
173 a BufferedRandom.
174
175 It is also possible to use a string or bytearray as a file for both
176 reading and writing. For strings StringIO can be used like a file
177 opened in a text mode, and for bytes a BytesIO can be used like a file
178 opened in a binary mode.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000179 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000180 if not isinstance(file, (str, int)):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000181 raise TypeError("invalid file: %r" % file)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000182 if not isinstance(mode, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000183 raise TypeError("invalid mode: %r" % mode)
184 if buffering is not None and not isinstance(buffering, int):
185 raise TypeError("invalid buffering: %r" % buffering)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000186 if encoding is not None and not isinstance(encoding, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000187 raise TypeError("invalid encoding: %r" % encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000188 if errors is not None and not isinstance(errors, str):
189 raise TypeError("invalid errors: %r" % errors)
Guido van Rossum28524c72007-02-27 05:47:44 +0000190 modes = set(mode)
Guido van Rossum9be55972007-04-07 02:59:27 +0000191 if modes - set("arwb+tU") or len(mode) > len(modes):
Guido van Rossum28524c72007-02-27 05:47:44 +0000192 raise ValueError("invalid mode: %r" % mode)
193 reading = "r" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000194 writing = "w" in modes
Guido van Rossum28524c72007-02-27 05:47:44 +0000195 appending = "a" in modes
196 updating = "+" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000197 text = "t" in modes
198 binary = "b" in modes
Guido van Rossum7165cb12007-07-10 06:54:34 +0000199 if "U" in modes:
200 if writing or appending:
201 raise ValueError("can't use U and writing mode at once")
Guido van Rossum9be55972007-04-07 02:59:27 +0000202 reading = True
Guido van Rossum28524c72007-02-27 05:47:44 +0000203 if text and binary:
204 raise ValueError("can't have text and binary mode at once")
205 if reading + writing + appending > 1:
206 raise ValueError("can't have read/write/append mode at once")
207 if not (reading or writing or appending):
208 raise ValueError("must have exactly one of read/write/append mode")
209 if binary and encoding is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +0000210 raise ValueError("binary mode doesn't take an encoding argument")
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000211 if binary and errors is not None:
212 raise ValueError("binary mode doesn't take an errors argument")
Guido van Rossum9b76da62007-04-11 01:09:03 +0000213 if binary and newline is not None:
214 raise ValueError("binary mode doesn't take a newline argument")
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000215 raw = FileIO(file,
Guido van Rossum28524c72007-02-27 05:47:44 +0000216 (reading and "r" or "") +
217 (writing and "w" or "") +
218 (appending and "a" or "") +
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000219 (updating and "+" or ""),
220 closefd)
Guido van Rossum28524c72007-02-27 05:47:44 +0000221 if buffering is None:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000222 buffering = -1
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000223 line_buffering = False
224 if buffering == 1 or buffering < 0 and raw.isatty():
225 buffering = -1
226 line_buffering = True
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000227 if buffering < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000228 buffering = DEFAULT_BUFFER_SIZE
Guido van Rossum17e43e52007-02-27 15:45:13 +0000229 try:
230 bs = os.fstat(raw.fileno()).st_blksize
231 except (os.error, AttributeError):
Guido van Rossumbb09b212007-03-18 03:36:28 +0000232 pass
233 else:
Guido van Rossum17e43e52007-02-27 15:45:13 +0000234 if bs > 1:
235 buffering = bs
Guido van Rossum28524c72007-02-27 05:47:44 +0000236 if buffering < 0:
237 raise ValueError("invalid buffering size")
238 if buffering == 0:
239 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000240 raw._name = file
241 raw._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000242 return raw
243 raise ValueError("can't have unbuffered text I/O")
244 if updating:
245 buffer = BufferedRandom(raw, buffering)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000246 elif writing or appending:
Guido van Rossum28524c72007-02-27 05:47:44 +0000247 buffer = BufferedWriter(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000248 elif reading:
Guido van Rossum28524c72007-02-27 05:47:44 +0000249 buffer = BufferedReader(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000250 else:
251 raise ValueError("unknown mode: %r" % mode)
Guido van Rossum28524c72007-02-27 05:47:44 +0000252 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000253 buffer.name = file
254 buffer.mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000255 return buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000256 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000257 text.name = file
258 text.mode = mode
259 return text
Guido van Rossum28524c72007-02-27 05:47:44 +0000260
Christian Heimesa33eb062007-12-08 17:47:40 +0000261class _DocDescriptor:
262 """Helper for builtins.open.__doc__
263 """
264 def __get__(self, obj, typ):
265 return (
266 "open(file, mode='r', buffering=None, encoding=None, "
267 "errors=None, newline=None, closefd=True)\n\n" +
268 open.__doc__)
Guido van Rossum28524c72007-02-27 05:47:44 +0000269
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000270class OpenWrapper:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000271 """Wrapper for builtins.open
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000272
273 Trick so that open won't become a bound method when stored
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000274 as a class variable (as dbm.dumb does).
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000275
276 See initstdio() in Python/pythonrun.c.
277 """
Christian Heimesa33eb062007-12-08 17:47:40 +0000278 __doc__ = _DocDescriptor()
279
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000280 def __new__(cls, *args, **kwargs):
281 return open(*args, **kwargs)
282
283
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000284class UnsupportedOperation(ValueError, IOError):
285 pass
286
287
Guido van Rossumb7f136e2007-08-22 18:14:10 +0000288class IOBase(metaclass=abc.ABCMeta):
Guido van Rossum28524c72007-02-27 05:47:44 +0000289
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000290 """The abstract base class for all I/O classes, acting on streams of
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000291 bytes. There is no public constructor.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000292
Guido van Rossum141f7672007-04-10 00:22:16 +0000293 This class provides dummy implementations for many methods that
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000294 derived classes can override selectively; the default implementations
295 represent a file that cannot be read, written or seeked.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000296
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000297 Even though IOBase does not declare read, readinto, or write because
298 their signatures will vary, implementations and clients should
299 consider those methods part of the interface. Also, implementations
300 may raise a IOError when operations they do not support are called.
Guido van Rossum53807da2007-04-10 19:01:47 +0000301
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000302 The basic type used for binary data read from or written to a file is
303 bytes. bytearrays are accepted too, and in some cases (such as
304 readinto) needed. Text I/O classes work with str data.
305
306 Note that calling any method (even inquiries) on a closed stream is
Benjamin Peterson9a89e962008-04-06 16:47:13 +0000307 undefined. Implementations may raise IOError in this case.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000308
309 IOBase (and its subclasses) support the iterator protocol, meaning
310 that an IOBase object can be iterated over yielding the lines in a
311 stream.
312
313 IOBase also supports the :keyword:`with` statement. In this example,
314 fp is closed after the suite of the with statment is complete:
315
316 with open('spam.txt', 'r') as fp:
317 fp.write('Spam and eggs!')
Guido van Rossum17e43e52007-02-27 15:45:13 +0000318 """
319
Guido van Rossum141f7672007-04-10 00:22:16 +0000320 ### Internal ###
321
322 def _unsupported(self, name: str) -> IOError:
323 """Internal: raise an exception for unsupported operations."""
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000324 raise UnsupportedOperation("%s.%s() not supported" %
325 (self.__class__.__name__, name))
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000326
Guido van Rossum141f7672007-04-10 00:22:16 +0000327 ### Positioning ###
328
Guido van Rossum53807da2007-04-10 19:01:47 +0000329 def seek(self, pos: int, whence: int = 0) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000330 """Change stream position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000331
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000332 Change the stream position to byte offset offset. offset is
333 interpreted relative to the position indicated by whence. Values
334 for whence are:
335
336 * 0 -- start of stream (the default); offset should be zero or positive
337 * 1 -- current stream position; offset may be negative
338 * 2 -- end of stream; offset is usually negative
339
340 Return the new absolute position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000341 """
342 self._unsupported("seek")
343
344 def tell(self) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000345 """Return current stream position."""
Guido van Rossum53807da2007-04-10 19:01:47 +0000346 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000347
Guido van Rossum87429772007-04-10 21:06:59 +0000348 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000349 """Truncate file to size bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000350
Christian Heimes5d8da202008-05-06 13:58:24 +0000351 Size defaults to the current IO position as reported by tell(). Return
352 the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000353 """
354 self._unsupported("truncate")
355
356 ### Flush and close ###
357
358 def flush(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000359 """Flush write buffers, if applicable.
Guido van Rossum141f7672007-04-10 00:22:16 +0000360
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000361 This is not implemented for read-only and non-blocking streams.
Guido van Rossum141f7672007-04-10 00:22:16 +0000362 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000363 # XXX Should this return the number of bytes written???
Guido van Rossum141f7672007-04-10 00:22:16 +0000364
365 __closed = False
366
367 def close(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000368 """Flush and close the IO object.
Guido van Rossum141f7672007-04-10 00:22:16 +0000369
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000370 This method has no effect if the file is already closed.
Guido van Rossum141f7672007-04-10 00:22:16 +0000371 """
372 if not self.__closed:
Guido van Rossum469734b2007-07-10 12:00:45 +0000373 try:
374 self.flush()
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000375 except IOError:
376 pass # If flush() fails, just give up
377 self.__closed = True
Guido van Rossum141f7672007-04-10 00:22:16 +0000378
379 def __del__(self) -> None:
380 """Destructor. Calls close()."""
381 # The try/except block is in case this is called at program
382 # exit time, when it's possible that globals have already been
383 # deleted, and then the close() call might fail. Since
384 # there's nothing we can do about such failures and they annoy
385 # the end users, we suppress the traceback.
386 try:
387 self.close()
388 except:
389 pass
390
391 ### Inquiries ###
392
393 def seekable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000394 """Return whether object supports random access.
Guido van Rossum141f7672007-04-10 00:22:16 +0000395
396 If False, seek(), tell() and truncate() will raise IOError.
397 This method may need to do a test seek().
398 """
399 return False
400
Guido van Rossum5abbf752007-08-27 17:39:33 +0000401 def _checkSeekable(self, msg=None):
402 """Internal: raise an IOError if file is not seekable
403 """
404 if not self.seekable():
405 raise IOError("File or stream is not seekable."
406 if msg is None else msg)
407
408
Guido van Rossum141f7672007-04-10 00:22:16 +0000409 def readable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000410 """Return whether object was opened for reading.
Guido van Rossum141f7672007-04-10 00:22:16 +0000411
412 If False, read() will raise IOError.
413 """
414 return False
415
Guido van Rossum5abbf752007-08-27 17:39:33 +0000416 def _checkReadable(self, msg=None):
417 """Internal: raise an IOError if file is not readable
418 """
419 if not self.readable():
420 raise IOError("File or stream is not readable."
421 if msg is None else msg)
422
Guido van Rossum141f7672007-04-10 00:22:16 +0000423 def writable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000424 """Return whether object was opened for writing.
Guido van Rossum141f7672007-04-10 00:22:16 +0000425
426 If False, write() and truncate() will raise IOError.
427 """
428 return False
429
Guido van Rossum5abbf752007-08-27 17:39:33 +0000430 def _checkWritable(self, msg=None):
431 """Internal: raise an IOError if file is not writable
432 """
433 if not self.writable():
434 raise IOError("File or stream is not writable."
435 if msg is None else msg)
436
Guido van Rossum141f7672007-04-10 00:22:16 +0000437 @property
438 def closed(self):
439 """closed: bool. True iff the file has been closed.
440
441 For backwards compatibility, this is a property, not a predicate.
442 """
443 return self.__closed
444
Guido van Rossum5abbf752007-08-27 17:39:33 +0000445 def _checkClosed(self, msg=None):
446 """Internal: raise an ValueError if file is closed
447 """
448 if self.closed:
449 raise ValueError("I/O operation on closed file."
450 if msg is None else msg)
451
Guido van Rossum141f7672007-04-10 00:22:16 +0000452 ### Context manager ###
453
454 def __enter__(self) -> "IOBase": # That's a forward reference
455 """Context management protocol. Returns self."""
Christian Heimes3ecfea712008-02-09 20:51:34 +0000456 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000457 return self
458
459 def __exit__(self, *args) -> None:
460 """Context management protocol. Calls close()"""
461 self.close()
462
463 ### Lower-level APIs ###
464
465 # XXX Should these be present even if unimplemented?
466
467 def fileno(self) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000468 """Returns underlying file descriptor if one exists.
Guido van Rossum141f7672007-04-10 00:22:16 +0000469
Christian Heimes5d8da202008-05-06 13:58:24 +0000470 An IOError is raised if the IO object does not use a file descriptor.
Guido van Rossum141f7672007-04-10 00:22:16 +0000471 """
472 self._unsupported("fileno")
473
474 def isatty(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000475 """Return whether this is an 'interactive' stream.
476
477 Return False if it can't be determined.
Guido van Rossum141f7672007-04-10 00:22:16 +0000478 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000479 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000480 return False
481
Guido van Rossum7165cb12007-07-10 06:54:34 +0000482 ### Readline[s] and writelines ###
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000483
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000484 def readline(self, limit: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000485 r"""Read and return a line from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000486
487 If limit is specified, at most limit bytes will be read.
488
489 The line terminator is always b'\n' for binary files; for text
490 files, the newlines argument to open can be used to select the line
491 terminator(s) recognized.
492 """
493 # For backwards compatibility, a (slowish) readline().
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000494 self._checkClosed()
Guido van Rossum2bf71382007-06-08 00:07:57 +0000495 if hasattr(self, "peek"):
496 def nreadahead():
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000497 readahead = self.peek(1)
Guido van Rossum2bf71382007-06-08 00:07:57 +0000498 if not readahead:
499 return 1
500 n = (readahead.find(b"\n") + 1) or len(readahead)
501 if limit >= 0:
502 n = min(n, limit)
503 return n
504 else:
505 def nreadahead():
506 return 1
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000507 if limit is None:
508 limit = -1
Guido van Rossum254348e2007-11-21 19:29:53 +0000509 res = bytearray()
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000510 while limit < 0 or len(res) < limit:
Guido van Rossum2bf71382007-06-08 00:07:57 +0000511 b = self.read(nreadahead())
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000512 if not b:
513 break
514 res += b
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000515 if res.endswith(b"\n"):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000516 break
Guido van Rossum98297ee2007-11-06 21:34:58 +0000517 return bytes(res)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000518
Guido van Rossum7165cb12007-07-10 06:54:34 +0000519 def __iter__(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000520 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000521 return self
522
523 def __next__(self):
524 line = self.readline()
525 if not line:
526 raise StopIteration
527 return line
528
529 def readlines(self, hint=None):
Christian Heimes5d8da202008-05-06 13:58:24 +0000530 """Return a list of lines from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000531
532 hint can be specified to control the number of lines read: no more
533 lines will be read if the total size (in bytes/characters) of all
534 lines so far exceeds hint.
535 """
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000536 if hint is None or hint <= 0:
Guido van Rossum7165cb12007-07-10 06:54:34 +0000537 return list(self)
538 n = 0
539 lines = []
540 for line in self:
541 lines.append(line)
542 n += len(line)
543 if n >= hint:
544 break
545 return lines
546
547 def writelines(self, lines):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000548 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000549 for line in lines:
550 self.write(line)
551
Guido van Rossum141f7672007-04-10 00:22:16 +0000552
553class RawIOBase(IOBase):
554
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000555 """Base class for raw binary I/O."""
Guido van Rossum141f7672007-04-10 00:22:16 +0000556
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000557 # The read() method is implemented by calling readinto(); derived
558 # classes that want to support read() only need to implement
559 # readinto() as a primitive operation. In general, readinto() can be
560 # more efficient than read().
Guido van Rossum141f7672007-04-10 00:22:16 +0000561
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000562 # (It would be tempting to also provide an implementation of
563 # readinto() in terms of read(), in case the latter is a more suitable
564 # primitive operation, but that would lead to nasty recursion in case
565 # a subclass doesn't implement either.)
Guido van Rossum141f7672007-04-10 00:22:16 +0000566
Guido van Rossum7165cb12007-07-10 06:54:34 +0000567 def read(self, n: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000568 """Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000569
Georg Brandlf91197c2008-04-09 07:33:01 +0000570 Returns an empty bytes object on EOF, or None if the object is
Guido van Rossum01a27522007-03-07 01:00:12 +0000571 set not to block and has no data to read.
572 """
Guido van Rossum7165cb12007-07-10 06:54:34 +0000573 if n is None:
574 n = -1
575 if n < 0:
576 return self.readall()
Guido van Rossum254348e2007-11-21 19:29:53 +0000577 b = bytearray(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000578 n = self.readinto(b)
579 del b[n:]
Guido van Rossum98297ee2007-11-06 21:34:58 +0000580 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000581
Guido van Rossum7165cb12007-07-10 06:54:34 +0000582 def readall(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000583 """Read until EOF, using multiple read() call."""
Guido van Rossum254348e2007-11-21 19:29:53 +0000584 res = bytearray()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000585 while True:
586 data = self.read(DEFAULT_BUFFER_SIZE)
587 if not data:
588 break
589 res += data
Guido van Rossum98297ee2007-11-06 21:34:58 +0000590 return bytes(res)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000591
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000592 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000593 """Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000594
595 Returns number of bytes read (0 for EOF), or None if the object
596 is set not to block as has no data to read.
597 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000598 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000599
Guido van Rossum141f7672007-04-10 00:22:16 +0000600 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000601 """Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000602
Guido van Rossum78892e42007-04-06 17:31:18 +0000603 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000604 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000605 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000606
Guido van Rossum78892e42007-04-06 17:31:18 +0000607
Guido van Rossum141f7672007-04-10 00:22:16 +0000608class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000609
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000610 """Raw I/O implementation for OS files."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000611
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000612 # This multiply inherits from _FileIO and RawIOBase to make
613 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
614 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
615 # to do since _fileio.c is written in C).
Guido van Rossuma9e20242007-03-08 00:43:48 +0000616
Guido van Rossum87429772007-04-10 21:06:59 +0000617 def close(self):
618 _fileio._FileIO.close(self)
619 RawIOBase.close(self)
620
Guido van Rossum13633bb2007-04-13 18:42:35 +0000621 @property
622 def name(self):
623 return self._name
624
Georg Brandlf91197c2008-04-09 07:33:01 +0000625 # XXX(gb): _FileIO already has a mode property
Guido van Rossum13633bb2007-04-13 18:42:35 +0000626 @property
627 def mode(self):
628 return self._mode
629
Guido van Rossuma9e20242007-03-08 00:43:48 +0000630
Guido van Rossumcce92b22007-04-10 14:41:39 +0000631class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000632
633 """Base class for buffered IO objects.
634
635 The main difference with RawIOBase is that the read() method
636 supports omitting the size argument, and does not have a default
637 implementation that defers to readinto().
638
639 In addition, read(), readinto() and write() may raise
640 BlockingIOError if the underlying raw stream is in non-blocking
641 mode and not ready; unlike their raw counterparts, they will never
642 return None.
643
644 A typical implementation should not inherit from a RawIOBase
645 implementation, but wrap one.
646 """
647
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000648 def read(self, n: int = None) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000649 """Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000650
Guido van Rossum024da5c2007-05-17 23:59:11 +0000651 If the argument is omitted, None, or negative, reads and
652 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000653
654 If the argument is positive, and the underlying raw stream is
655 not 'interactive', multiple raw reads may be issued to satisfy
656 the byte count (unless EOF is reached first). But for
657 interactive raw streams (XXX and for pipes?), at most one raw
658 read will be issued, and a short result does not imply that
659 EOF is imminent.
660
661 Returns an empty bytes array on EOF.
662
663 Raises BlockingIOError if the underlying raw stream has no
664 data at the moment.
665 """
666 self._unsupported("read")
667
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000668 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000669 """Read up to len(b) bytes into b.
Guido van Rossum141f7672007-04-10 00:22:16 +0000670
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000671 Like read(), this may issue multiple reads to the underlying raw
672 stream, unless the latter is 'interactive'.
Guido van Rossum141f7672007-04-10 00:22:16 +0000673
674 Returns the number of bytes read (0 for EOF).
675
676 Raises BlockingIOError if the underlying raw stream has no
677 data at the moment.
678 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000679 # XXX This ought to work with anything that supports the buffer API
Guido van Rossum87429772007-04-10 21:06:59 +0000680 data = self.read(len(b))
681 n = len(data)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000682 try:
683 b[:n] = data
684 except TypeError as err:
685 import array
686 if not isinstance(b, array.array):
687 raise err
688 b[:n] = array.array('b', data)
Guido van Rossum87429772007-04-10 21:06:59 +0000689 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000690
691 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000692 """Write the given buffer to the IO stream.
Guido van Rossum141f7672007-04-10 00:22:16 +0000693
Christian Heimes5d8da202008-05-06 13:58:24 +0000694 Return the number of bytes written, which is never less than
Guido van Rossum141f7672007-04-10 00:22:16 +0000695 len(b).
696
697 Raises BlockingIOError if the buffer is full and the
698 underlying raw stream cannot accept more data at the moment.
699 """
700 self._unsupported("write")
701
702
703class _BufferedIOMixin(BufferedIOBase):
704
705 """A mixin implementation of BufferedIOBase with an underlying raw stream.
706
707 This passes most requests on to the underlying raw stream. It
708 does *not* provide implementations of read(), readinto() or
709 write().
710 """
711
712 def __init__(self, raw):
713 self.raw = raw
714
715 ### Positioning ###
716
717 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000718 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000719
720 def tell(self):
721 return self.raw.tell()
722
723 def truncate(self, pos=None):
Guido van Rossum79b79ee2007-10-25 23:21:03 +0000724 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
725 # and a flush may be necessary to synch both views of the current
726 # file state.
727 self.flush()
Guido van Rossum57233cb2007-10-26 17:19:33 +0000728
729 if pos is None:
730 pos = self.tell()
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000731 # XXX: Should seek() be used, instead of passing the position
732 # XXX directly to truncate?
Guido van Rossum57233cb2007-10-26 17:19:33 +0000733 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000734
735 ### Flush and close ###
736
737 def flush(self):
738 self.raw.flush()
739
740 def close(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000741 if not self.closed:
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000742 try:
743 self.flush()
744 except IOError:
745 pass # If flush() fails, just give up
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000746 self.raw.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000747
748 ### Inquiries ###
749
750 def seekable(self):
751 return self.raw.seekable()
752
753 def readable(self):
754 return self.raw.readable()
755
756 def writable(self):
757 return self.raw.writable()
758
759 @property
760 def closed(self):
761 return self.raw.closed
762
763 ### Lower-level APIs ###
764
765 def fileno(self):
766 return self.raw.fileno()
767
768 def isatty(self):
769 return self.raw.isatty()
770
771
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000772class _BytesIO(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000773
Guido van Rossum024da5c2007-05-17 23:59:11 +0000774 """Buffered I/O implementation using an in-memory bytes buffer."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000775
Guido van Rossum024da5c2007-05-17 23:59:11 +0000776 def __init__(self, initial_bytes=None):
Guido van Rossum254348e2007-11-21 19:29:53 +0000777 buf = bytearray()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000778 if initial_bytes is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000779 buf += initial_bytes
780 self._buffer = buf
Guido van Rossum28524c72007-02-27 05:47:44 +0000781 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000782
783 def getvalue(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000784 """Return the bytes value (contents) of the buffer
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000785 """
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000786 if self.closed:
787 raise ValueError("getvalue on closed file")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000788 return bytes(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000789
Guido van Rossum024da5c2007-05-17 23:59:11 +0000790 def read(self, n=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000791 if self.closed:
792 raise ValueError("read from closed file")
Guido van Rossum024da5c2007-05-17 23:59:11 +0000793 if n is None:
794 n = -1
Guido van Rossum141f7672007-04-10 00:22:16 +0000795 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000796 n = len(self._buffer)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000797 if len(self._buffer) <= self._pos:
Alexandre Vassalotti2e0419d2008-05-07 00:09:04 +0000798 return b""
Guido van Rossum28524c72007-02-27 05:47:44 +0000799 newpos = min(len(self._buffer), self._pos + n)
800 b = self._buffer[self._pos : newpos]
801 self._pos = newpos
Guido van Rossum98297ee2007-11-06 21:34:58 +0000802 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000803
Guido van Rossum024da5c2007-05-17 23:59:11 +0000804 def read1(self, n):
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000805 """This is the same as read.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000806 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000807 return self.read(n)
808
Guido van Rossum28524c72007-02-27 05:47:44 +0000809 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000810 if self.closed:
811 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +0000812 if isinstance(b, str):
813 raise TypeError("can't write str to binary stream")
Guido van Rossum28524c72007-02-27 05:47:44 +0000814 n = len(b)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000815 if n == 0:
816 return 0
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000817 pos = self._pos
818 if pos > len(self._buffer):
Guido van Rossumb972a782007-07-21 00:25:15 +0000819 # Inserts null bytes between the current end of the file
820 # and the new write position.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000821 padding = b'\x00' * (pos - len(self._buffer))
822 self._buffer += padding
823 self._buffer[pos:pos + n] = b
824 self._pos += n
Guido van Rossum28524c72007-02-27 05:47:44 +0000825 return n
826
827 def seek(self, pos, whence=0):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000828 if self.closed:
829 raise ValueError("seek on closed file")
Christian Heimes3ab4f652007-11-09 01:27:29 +0000830 try:
831 pos = pos.__index__()
832 except AttributeError as err:
833 raise TypeError("an integer is required") from err
Guido van Rossum28524c72007-02-27 05:47:44 +0000834 if whence == 0:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000835 if pos < 0:
836 raise ValueError("negative seek position %r" % (pos,))
Alexandre Vassalottif0c0ff62008-05-09 21:21:21 +0000837 self._pos = pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000838 elif whence == 1:
839 self._pos = max(0, self._pos + pos)
840 elif whence == 2:
841 self._pos = max(0, len(self._buffer) + pos)
842 else:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000843 raise ValueError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000844 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000845
846 def tell(self):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000847 if self.closed:
848 raise ValueError("tell on closed file")
Guido van Rossum28524c72007-02-27 05:47:44 +0000849 return self._pos
850
851 def truncate(self, pos=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000852 if self.closed:
853 raise ValueError("truncate on closed file")
Guido van Rossum28524c72007-02-27 05:47:44 +0000854 if pos is None:
855 pos = self._pos
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000856 elif pos < 0:
857 raise ValueError("negative truncate position %r" % (pos,))
Guido van Rossum28524c72007-02-27 05:47:44 +0000858 del self._buffer[pos:]
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000859 return self.seek(pos)
Guido van Rossum28524c72007-02-27 05:47:44 +0000860
861 def readable(self):
862 return True
863
864 def writable(self):
865 return True
866
867 def seekable(self):
868 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000869
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000870# Use the faster implementation of BytesIO if available
871try:
872 import _bytesio
873
874 class BytesIO(_bytesio._BytesIO, BufferedIOBase):
875 __doc__ = _bytesio._BytesIO.__doc__
876
877except ImportError:
878 BytesIO = _BytesIO
879
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000880
Guido van Rossum141f7672007-04-10 00:22:16 +0000881class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000882
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000883 """BufferedReader(raw[, buffer_size])
884
885 A buffer for a readable, sequential BaseRawIO object.
886
887 The constructor creates a BufferedReader for the given readable raw
888 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
889 is used.
890 """
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000891
Guido van Rossum78892e42007-04-06 17:31:18 +0000892 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000893 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000894 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000895 raw._checkReadable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000896 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum78892e42007-04-06 17:31:18 +0000897 self.buffer_size = buffer_size
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000898 self._reset_read_buf()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +0000899 self._read_lock = Lock()
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000900
901 def _reset_read_buf(self):
902 self._read_buf = b""
903 self._read_pos = 0
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000904
Guido van Rossum024da5c2007-05-17 23:59:11 +0000905 def read(self, n=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000906 """Read n bytes.
907
908 Returns exactly n bytes of data unless the underlying raw IO
Walter Dörwalda3270002007-05-29 19:13:29 +0000909 stream reaches EOF or if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000910 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000911 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000912 """
Antoine Pitrou87695762008-08-14 22:44:29 +0000913 with self._read_lock:
914 return self._read_unlocked(n)
915
916 def _read_unlocked(self, n=None):
Guido van Rossum78892e42007-04-06 17:31:18 +0000917 nodata_val = b""
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000918 empty_values = (b"", None)
919 buf = self._read_buf
920 pos = self._read_pos
921
922 # Special case for when the number of bytes to read is unspecified.
923 if n is None or n == -1:
924 self._reset_read_buf()
925 chunks = [buf[pos:]] # Strip the consumed bytes.
926 current_size = 0
927 while True:
928 # Read until EOF or until read() would block.
929 chunk = self.raw.read()
930 if chunk in empty_values:
931 nodata_val = chunk
932 break
933 current_size += len(chunk)
934 chunks.append(chunk)
935 return b"".join(chunks) or nodata_val
936
937 # The number of bytes to read is specified, return at most n bytes.
938 avail = len(buf) - pos # Length of the available buffered data.
939 if n <= avail:
940 # Fast path: the data to read is fully buffered.
941 self._read_pos += n
942 return buf[pos:pos+n]
943 # Slow path: read from the stream until enough bytes are read,
944 # or until an EOF occurs or until read() would block.
945 chunks = [buf[pos:]]
946 wanted = max(self.buffer_size, n)
947 while avail < n:
948 chunk = self.raw.read(wanted)
949 if chunk in empty_values:
950 nodata_val = chunk
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000951 break
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000952 avail += len(chunk)
953 chunks.append(chunk)
954 # n is more then avail only when an EOF occurred or when
955 # read() would have blocked.
956 n = min(n, avail)
957 out = b"".join(chunks)
958 self._read_buf = out[n:] # Save the extra data in the buffer.
959 self._read_pos = 0
960 return out[:n] if out else nodata_val
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000961
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000962 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000963 """Returns buffered bytes without advancing the position.
964
965 The argument indicates a desired minimal number of bytes; we
966 do at most one raw read to satisfy it. We never return more
967 than self.buffer_size.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000968 """
Antoine Pitrou87695762008-08-14 22:44:29 +0000969 with self._read_lock:
970 return self._peek_unlocked(n)
971
972 def _peek_unlocked(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000973 want = min(n, self.buffer_size)
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000974 have = len(self._read_buf) - self._read_pos
Guido van Rossum13633bb2007-04-13 18:42:35 +0000975 if have < want:
976 to_read = self.buffer_size - have
977 current = self.raw.read(to_read)
978 if current:
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000979 self._read_buf = self._read_buf[self._read_pos:] + current
980 self._read_pos = 0
981 return self._read_buf[self._read_pos:]
Guido van Rossum13633bb2007-04-13 18:42:35 +0000982
983 def read1(self, n):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000984 """Reads up to n bytes, with at most one read() system call."""
985 # Returns up to n bytes. If at least one byte is buffered, we
986 # only return buffered bytes. Otherwise, we do one raw read.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000987 if n <= 0:
988 return b""
Antoine Pitrou87695762008-08-14 22:44:29 +0000989 with self._read_lock:
990 self._peek_unlocked(1)
991 return self._read_unlocked(
992 min(n, len(self._read_buf) - self._read_pos))
Guido van Rossum13633bb2007-04-13 18:42:35 +0000993
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000994 def tell(self):
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000995 return self.raw.tell() - len(self._read_buf) + self._read_pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000996
997 def seek(self, pos, whence=0):
Antoine Pitrou87695762008-08-14 22:44:29 +0000998 with self._read_lock:
999 if whence == 1:
1000 pos -= len(self._read_buf) - self._read_pos
1001 pos = self.raw.seek(pos, whence)
1002 self._reset_read_buf()
1003 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001004
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001005
Guido van Rossum141f7672007-04-10 00:22:16 +00001006class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001007
Christian Heimes5d8da202008-05-06 13:58:24 +00001008 """A buffer for a writeable sequential RawIO object.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001009
1010 The constructor creates a BufferedWriter for the given writeable raw
1011 stream. If the buffer_size is not given, it defaults to
1012 DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
1013 twice the buffer size.
1014 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001015
Guido van Rossum141f7672007-04-10 00:22:16 +00001016 def __init__(self, raw,
1017 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001018 raw._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001019 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001020 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +00001021 self.max_buffer_size = (2*buffer_size
1022 if max_buffer_size is None
1023 else max_buffer_size)
Guido van Rossum254348e2007-11-21 19:29:53 +00001024 self._write_buf = bytearray()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +00001025 self._write_lock = Lock()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001026
1027 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001028 if self.closed:
1029 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +00001030 if isinstance(b, str):
1031 raise TypeError("can't write str to binary stream")
Antoine Pitrou87695762008-08-14 22:44:29 +00001032 with self._write_lock:
1033 # XXX we can implement some more tricks to try and avoid
1034 # partial writes
1035 if len(self._write_buf) > self.buffer_size:
1036 # We're full, so let's pre-flush the buffer
1037 try:
1038 self._flush_unlocked()
1039 except BlockingIOError as e:
1040 # We can't accept anything else.
1041 # XXX Why not just let the exception pass through?
1042 raise BlockingIOError(e.errno, e.strerror, 0)
1043 before = len(self._write_buf)
1044 self._write_buf.extend(b)
1045 written = len(self._write_buf) - before
1046 if len(self._write_buf) > self.buffer_size:
1047 try:
1048 self._flush_unlocked()
1049 except BlockingIOError as e:
1050 if len(self._write_buf) > self.max_buffer_size:
1051 # We've hit max_buffer_size. We have to accept a
1052 # partial write and cut back our buffer.
1053 overage = len(self._write_buf) - self.max_buffer_size
1054 self._write_buf = self._write_buf[:self.max_buffer_size]
1055 raise BlockingIOError(e.errno, e.strerror, overage)
1056 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001057
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001058 def truncate(self, pos=None):
Antoine Pitrou87695762008-08-14 22:44:29 +00001059 with self._write_lock:
1060 self._flush_unlocked()
1061 if pos is None:
1062 pos = self.raw.tell()
1063 return self.raw.truncate(pos)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001064
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001065 def flush(self):
Antoine Pitrou87695762008-08-14 22:44:29 +00001066 with self._write_lock:
1067 self._flush_unlocked()
1068
1069 def _flush_unlocked(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001070 if self.closed:
1071 raise ValueError("flush of closed file")
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001072 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +00001073 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001074 while self._write_buf:
1075 n = self.raw.write(self._write_buf)
1076 del self._write_buf[:n]
1077 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001078 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001079 n = e.characters_written
1080 del self._write_buf[:n]
1081 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001082 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001083
1084 def tell(self):
1085 return self.raw.tell() + len(self._write_buf)
1086
1087 def seek(self, pos, whence=0):
Antoine Pitrou87695762008-08-14 22:44:29 +00001088 with self._write_lock:
1089 self._flush_unlocked()
1090 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001091
Guido van Rossum01a27522007-03-07 01:00:12 +00001092
Guido van Rossum141f7672007-04-10 00:22:16 +00001093class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001094
Guido van Rossum01a27522007-03-07 01:00:12 +00001095 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001096
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001097 A buffered reader object and buffered writer object put together to
1098 form a sequential IO object that can read and write. This is typically
1099 used with a socket or two-way pipe.
Guido van Rossum78892e42007-04-06 17:31:18 +00001100
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001101 reader and writer are RawIOBase objects that are readable and
1102 writeable respectively. If the buffer_size is omitted it defaults to
1103 DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
1104 defaults to twice the buffer size.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001105 """
1106
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001107 # XXX The usefulness of this (compared to having two separate IO
1108 # objects) is questionable.
1109
Guido van Rossum141f7672007-04-10 00:22:16 +00001110 def __init__(self, reader, writer,
1111 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1112 """Constructor.
1113
1114 The arguments are two RawIO instances.
1115 """
Guido van Rossum5abbf752007-08-27 17:39:33 +00001116 reader._checkReadable()
1117 writer._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001118 self.reader = BufferedReader(reader, buffer_size)
1119 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001120
Guido van Rossum024da5c2007-05-17 23:59:11 +00001121 def read(self, n=None):
1122 if n is None:
1123 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001124 return self.reader.read(n)
1125
Guido van Rossum141f7672007-04-10 00:22:16 +00001126 def readinto(self, b):
1127 return self.reader.readinto(b)
1128
Guido van Rossum01a27522007-03-07 01:00:12 +00001129 def write(self, b):
1130 return self.writer.write(b)
1131
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001132 def peek(self, n=0):
1133 return self.reader.peek(n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001134
1135 def read1(self, n):
1136 return self.reader.read1(n)
1137
Guido van Rossum01a27522007-03-07 01:00:12 +00001138 def readable(self):
1139 return self.reader.readable()
1140
1141 def writable(self):
1142 return self.writer.writable()
1143
1144 def flush(self):
1145 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001146
Guido van Rossum01a27522007-03-07 01:00:12 +00001147 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +00001148 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +00001149 self.reader.close()
1150
1151 def isatty(self):
1152 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +00001153
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001154 @property
1155 def closed(self):
Guido van Rossum141f7672007-04-10 00:22:16 +00001156 return self.writer.closed()
Guido van Rossum01a27522007-03-07 01:00:12 +00001157
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001158
Guido van Rossum141f7672007-04-10 00:22:16 +00001159class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +00001160
Christian Heimes5d8da202008-05-06 13:58:24 +00001161 """A buffered interface to random access streams.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001162
1163 The constructor creates a reader and writer for a seekable stream,
1164 raw, given in the first argument. If the buffer_size is omitted it
1165 defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
1166 writer) defaults to twice the buffer size.
1167 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001168
Guido van Rossum141f7672007-04-10 00:22:16 +00001169 def __init__(self, raw,
1170 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001171 raw._checkSeekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001172 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001173 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1174
Guido van Rossum01a27522007-03-07 01:00:12 +00001175 def seek(self, pos, whence=0):
1176 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001177 # First do the raw seek, then empty the read buffer, so that
1178 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +00001179 pos = self.raw.seek(pos, whence)
Antoine Pitrou87695762008-08-14 22:44:29 +00001180 with self._read_lock:
1181 self._reset_read_buf()
Guido van Rossum53807da2007-04-10 19:01:47 +00001182 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +00001183
1184 def tell(self):
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001185 if self._write_buf:
Guido van Rossum01a27522007-03-07 01:00:12 +00001186 return self.raw.tell() + len(self._write_buf)
1187 else:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001188 return BufferedReader.tell(self)
Guido van Rossum01a27522007-03-07 01:00:12 +00001189
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001190 def truncate(self, pos=None):
1191 if pos is None:
1192 pos = self.tell()
1193 # Use seek to flush the read buffer.
1194 self.seek(pos)
1195 return BufferedWriter.truncate(self)
1196
Guido van Rossum024da5c2007-05-17 23:59:11 +00001197 def read(self, n=None):
1198 if n is None:
1199 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001200 self.flush()
1201 return BufferedReader.read(self, n)
1202
Guido van Rossum141f7672007-04-10 00:22:16 +00001203 def readinto(self, b):
1204 self.flush()
1205 return BufferedReader.readinto(self, b)
1206
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001207 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +00001208 self.flush()
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001209 return BufferedReader.peek(self, n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001210
1211 def read1(self, n):
1212 self.flush()
1213 return BufferedReader.read1(self, n)
1214
Guido van Rossum01a27522007-03-07 01:00:12 +00001215 def write(self, b):
Guido van Rossum78892e42007-04-06 17:31:18 +00001216 if self._read_buf:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001217 # Undo readahead
Antoine Pitrou87695762008-08-14 22:44:29 +00001218 with self._read_lock:
1219 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1220 self._reset_read_buf()
Guido van Rossum01a27522007-03-07 01:00:12 +00001221 return BufferedWriter.write(self, b)
1222
Guido van Rossum78892e42007-04-06 17:31:18 +00001223
Guido van Rossumcce92b22007-04-10 14:41:39 +00001224class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +00001225
1226 """Base class for text I/O.
1227
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001228 This class provides a character and line based interface to stream
1229 I/O. There is no readinto method because Python's character strings
1230 are immutable. There is no public constructor.
Guido van Rossum78892e42007-04-06 17:31:18 +00001231 """
1232
1233 def read(self, n: int = -1) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001234 """Read at most n characters from stream.
Guido van Rossum78892e42007-04-06 17:31:18 +00001235
1236 Read from underlying buffer until we have n characters or we hit EOF.
1237 If n is negative or omitted, read until EOF.
1238 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001239 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +00001240
Guido van Rossum9b76da62007-04-11 01:09:03 +00001241 def write(self, s: str) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001242 """Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001243 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +00001244
Guido van Rossum9b76da62007-04-11 01:09:03 +00001245 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001246 """Truncate size to pos."""
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001247 self._unsupported("truncate")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001248
Guido van Rossum78892e42007-04-06 17:31:18 +00001249 def readline(self) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001250 """Read until newline or EOF.
Guido van Rossum78892e42007-04-06 17:31:18 +00001251
1252 Returns an empty string if EOF is hit immediately.
1253 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001254 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +00001255
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001256 @property
1257 def encoding(self):
1258 """Subclasses should override."""
1259 return None
1260
Guido van Rossum8358db22007-08-18 21:39:55 +00001261 @property
1262 def newlines(self):
Christian Heimes5d8da202008-05-06 13:58:24 +00001263 """Line endings translated so far.
Guido van Rossum8358db22007-08-18 21:39:55 +00001264
1265 Only line endings translated during reading are considered.
1266
1267 Subclasses should override.
1268 """
1269 return None
1270
Guido van Rossum78892e42007-04-06 17:31:18 +00001271
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001272class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001273 r"""Codec used when reading a file in universal newlines mode. It wraps
1274 another incremental decoder, translating \r\n and \r into \n. It also
1275 records the types of newlines encountered. When used with
1276 translate=False, it ensures that the newline sequence is returned in
1277 one piece.
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001278 """
1279 def __init__(self, decoder, translate, errors='strict'):
1280 codecs.IncrementalDecoder.__init__(self, errors=errors)
1281 self.buffer = b''
1282 self.translate = translate
1283 self.decoder = decoder
1284 self.seennl = 0
1285
1286 def decode(self, input, final=False):
1287 # decode input (with the eventual \r from a previous pass)
1288 if self.buffer:
1289 input = self.buffer + input
1290
1291 output = self.decoder.decode(input, final=final)
1292
1293 # retain last \r even when not translating data:
1294 # then readline() is sure to get \r\n in one pass
1295 if output.endswith("\r") and not final:
1296 output = output[:-1]
1297 self.buffer = b'\r'
1298 else:
1299 self.buffer = b''
1300
1301 # Record which newlines are read
1302 crlf = output.count('\r\n')
1303 cr = output.count('\r') - crlf
1304 lf = output.count('\n') - crlf
1305 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1306 | (crlf and self._CRLF)
1307
1308 if self.translate:
1309 if crlf:
1310 output = output.replace("\r\n", "\n")
1311 if cr:
1312 output = output.replace("\r", "\n")
1313
1314 return output
1315
1316 def getstate(self):
1317 buf, flag = self.decoder.getstate()
1318 return buf + self.buffer, flag
1319
1320 def setstate(self, state):
1321 buf, flag = state
1322 if buf.endswith(b'\r'):
1323 self.buffer = b'\r'
1324 buf = buf[:-1]
1325 else:
1326 self.buffer = b''
1327 self.decoder.setstate((buf, flag))
1328
1329 def reset(self):
Alexandre Vassalottic3d7fe02007-12-28 01:24:22 +00001330 self.seennl = 0
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001331 self.buffer = b''
1332 self.decoder.reset()
1333
1334 _LF = 1
1335 _CR = 2
1336 _CRLF = 4
1337
1338 @property
1339 def newlines(self):
1340 return (None,
1341 "\n",
1342 "\r",
1343 ("\r", "\n"),
1344 "\r\n",
1345 ("\n", "\r\n"),
1346 ("\r", "\r\n"),
1347 ("\r", "\n", "\r\n")
1348 )[self.seennl]
1349
1350
Guido van Rossum78892e42007-04-06 17:31:18 +00001351class TextIOWrapper(TextIOBase):
1352
Christian Heimes5d8da202008-05-06 13:58:24 +00001353 r"""Character and line based layer over a BufferedIOBase object, buffer.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001354
1355 encoding gives the name of the encoding that the stream will be
1356 decoded or encoded with. It defaults to locale.getpreferredencoding.
1357
1358 errors determines the strictness of encoding and decoding (see the
1359 codecs.register) and defaults to "strict".
1360
1361 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1362 handling of line endings. If it is None, universal newlines is
1363 enabled. With this enabled, on input, the lines endings '\n', '\r',
1364 or '\r\n' are translated to '\n' before being returned to the
1365 caller. Conversely, on output, '\n' is translated to the system
1366 default line seperator, os.linesep. If newline is any other of its
1367 legal values, that newline becomes the newline when the file is read
1368 and it is returned untranslated. On output, '\n' is converted to the
1369 newline.
1370
1371 If line_buffering is True, a call to flush is implied when a call to
1372 write contains a newline character.
Guido van Rossum78892e42007-04-06 17:31:18 +00001373 """
1374
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001375 _CHUNK_SIZE = 128
Guido van Rossum78892e42007-04-06 17:31:18 +00001376
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001377 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1378 line_buffering=False):
Guido van Rossum8358db22007-08-18 21:39:55 +00001379 if newline not in (None, "", "\n", "\r", "\r\n"):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001380 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +00001381 if encoding is None:
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001382 try:
1383 encoding = os.device_encoding(buffer.fileno())
Brett Cannon041683d2007-10-11 23:08:53 +00001384 except (AttributeError, UnsupportedOperation):
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001385 pass
1386 if encoding is None:
Martin v. Löwisd78d3b42007-08-11 15:36:45 +00001387 try:
1388 import locale
1389 except ImportError:
1390 # Importing locale may fail if Python is being built
1391 encoding = "ascii"
1392 else:
1393 encoding = locale.getpreferredencoding()
Guido van Rossum78892e42007-04-06 17:31:18 +00001394
Christian Heimes8bd14fb2007-11-08 16:34:32 +00001395 if not isinstance(encoding, str):
1396 raise ValueError("invalid encoding: %r" % encoding)
1397
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001398 if errors is None:
1399 errors = "strict"
1400 else:
1401 if not isinstance(errors, str):
1402 raise ValueError("invalid errors: %r" % errors)
1403
Guido van Rossum78892e42007-04-06 17:31:18 +00001404 self.buffer = buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001405 self._line_buffering = line_buffering
Guido van Rossum78892e42007-04-06 17:31:18 +00001406 self._encoding = encoding
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001407 self._errors = errors
Guido van Rossum8358db22007-08-18 21:39:55 +00001408 self._readuniversal = not newline
1409 self._readtranslate = newline is None
1410 self._readnl = newline
1411 self._writetranslate = newline != ''
1412 self._writenl = newline or os.linesep
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001413 self._encoder = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001414 self._decoder = None
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001415 self._decoded_chars = '' # buffer for text returned from decoder
1416 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001417 self._snapshot = None # info for reconstructing decoder state
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001418 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001419
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001420 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1421 # where dec_flags is the second (integer) item of the decoder state
1422 # and next_input is the chunk of input bytes that comes next after the
1423 # snapshot point. We use this to reconstruct decoder states in tell().
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001424
1425 # Naming convention:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001426 # - "bytes_..." for integer variables that count input bytes
1427 # - "chars_..." for integer variables that count decoded characters
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001428
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001429 @property
1430 def encoding(self):
1431 return self._encoding
1432
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001433 @property
1434 def errors(self):
1435 return self._errors
1436
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001437 @property
1438 def line_buffering(self):
1439 return self._line_buffering
1440
Ka-Ping Yeeddaa7062008-03-17 20:35:15 +00001441 def seekable(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001442 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +00001443
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001444 def readable(self):
1445 return self.buffer.readable()
1446
1447 def writable(self):
1448 return self.buffer.writable()
1449
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001450 def flush(self):
1451 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001452 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001453
1454 def close(self):
Guido van Rossum33e7a8e2007-07-22 20:38:07 +00001455 try:
1456 self.flush()
1457 except:
1458 pass # If flush() fails, just give up
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001459 self.buffer.close()
1460
1461 @property
1462 def closed(self):
1463 return self.buffer.closed
1464
Guido van Rossum9be55972007-04-07 02:59:27 +00001465 def fileno(self):
1466 return self.buffer.fileno()
1467
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001468 def isatty(self):
1469 return self.buffer.isatty()
1470
Guido van Rossum78892e42007-04-06 17:31:18 +00001471 def write(self, s: str):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001472 if self.closed:
1473 raise ValueError("write to closed file")
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001474 if not isinstance(s, str):
Guido van Rossumdcce8392007-08-29 18:10:08 +00001475 raise TypeError("can't write %s to text stream" %
1476 s.__class__.__name__)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001477 length = len(s)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001478 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
Guido van Rossum8358db22007-08-18 21:39:55 +00001479 if haslf and self._writetranslate and self._writenl != "\n":
1480 s = s.replace("\n", self._writenl)
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001481 encoder = self._encoder or self._get_encoder()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001482 # XXX What if we were just reading?
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001483 b = encoder.encode(s)
Guido van Rossum8358db22007-08-18 21:39:55 +00001484 self.buffer.write(b)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001485 if self._line_buffering and (haslf or "\r" in s):
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001486 self.flush()
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001487 self._snapshot = None
1488 if self._decoder:
1489 self._decoder.reset()
1490 return length
Guido van Rossum78892e42007-04-06 17:31:18 +00001491
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001492 def _get_encoder(self):
1493 make_encoder = codecs.getincrementalencoder(self._encoding)
1494 self._encoder = make_encoder(self._errors)
1495 return self._encoder
1496
Guido van Rossum78892e42007-04-06 17:31:18 +00001497 def _get_decoder(self):
1498 make_decoder = codecs.getincrementaldecoder(self._encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001499 decoder = make_decoder(self._errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001500 if self._readuniversal:
1501 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1502 self._decoder = decoder
Guido van Rossum78892e42007-04-06 17:31:18 +00001503 return decoder
1504
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001505 # The following three methods implement an ADT for _decoded_chars.
1506 # Text returned from the decoder is buffered here until the client
1507 # requests it by calling our read() or readline() method.
1508 def _set_decoded_chars(self, chars):
1509 """Set the _decoded_chars buffer."""
1510 self._decoded_chars = chars
1511 self._decoded_chars_used = 0
1512
1513 def _get_decoded_chars(self, n=None):
1514 """Advance into the _decoded_chars buffer."""
1515 offset = self._decoded_chars_used
1516 if n is None:
1517 chars = self._decoded_chars[offset:]
1518 else:
1519 chars = self._decoded_chars[offset:offset + n]
1520 self._decoded_chars_used += len(chars)
1521 return chars
1522
1523 def _rewind_decoded_chars(self, n):
1524 """Rewind the _decoded_chars buffer."""
1525 if self._decoded_chars_used < n:
1526 raise AssertionError("rewind decoded_chars out of bounds")
1527 self._decoded_chars_used -= n
1528
Guido van Rossum9b76da62007-04-11 01:09:03 +00001529 def _read_chunk(self):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001530 """
1531 Read and decode the next chunk of data from the BufferedReader.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001532 """
1533
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001534 # The return value is True unless EOF was reached. The decoded
1535 # string is placed in self._decoded_chars (replacing its previous
1536 # value). The entire input chunk is sent to the decoder, though
1537 # some of it may remain buffered in the decoder, yet to be
1538 # converted.
1539
Guido van Rossum5abbf752007-08-27 17:39:33 +00001540 if self._decoder is None:
1541 raise ValueError("no decoder")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001542
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001543 if self._telling:
1544 # To prepare for tell(), we need to snapshot a point in the
1545 # file where the decoder's input buffer is empty.
Guido van Rossum9b76da62007-04-11 01:09:03 +00001546
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001547 dec_buffer, dec_flags = self._decoder.getstate()
1548 # Given this, we know there was a valid snapshot point
1549 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001550
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001551 # Read a chunk, decode it, and put the result in self._decoded_chars.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001552 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1553 eof = not input_chunk
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001554 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001555
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001556 if self._telling:
1557 # At the snapshot point, len(dec_buffer) bytes before the read,
1558 # the next input to be decoded is dec_buffer + input_chunk.
1559 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1560
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001561 return not eof
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001562
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001563 def _pack_cookie(self, position, dec_flags=0,
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001564 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001565 # The meaning of a tell() cookie is: seek to position, set the
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001566 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001567 # into the decoder with need_eof as the EOF flag, then skip
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001568 # chars_to_skip characters of the decoded result. For most simple
1569 # decoders, tell() will often just give a byte offset in the file.
1570 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1571 (chars_to_skip<<192) | bool(need_eof)<<256)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001572
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001573 def _unpack_cookie(self, bigint):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001574 rest, position = divmod(bigint, 1<<64)
1575 rest, dec_flags = divmod(rest, 1<<64)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001576 rest, bytes_to_feed = divmod(rest, 1<<64)
1577 need_eof, chars_to_skip = divmod(rest, 1<<64)
1578 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
Guido van Rossum9b76da62007-04-11 01:09:03 +00001579
1580 def tell(self):
1581 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001582 raise IOError("underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001583 if not self._telling:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001584 raise IOError("telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001585 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001586 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001587 decoder = self._decoder
1588 if decoder is None or self._snapshot is None:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001589 if self._decoded_chars:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001590 # This should never happen.
1591 raise AssertionError("pending decoded text")
Guido van Rossumcba608c2007-04-11 14:19:59 +00001592 return position
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001593
1594 # Skip backward to the snapshot point (see _read_chunk).
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001595 dec_flags, next_input = self._snapshot
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001596 position -= len(next_input)
1597
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001598 # How many decoded characters have been used up since the snapshot?
1599 chars_to_skip = self._decoded_chars_used
1600 if chars_to_skip == 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001601 # We haven't moved from the snapshot point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001602 return self._pack_cookie(position, dec_flags)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001603
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001604 # Starting from the snapshot position, we will walk the decoder
1605 # forward until it gives us enough decoded characters.
Guido van Rossumd76e7792007-04-17 02:38:04 +00001606 saved_state = decoder.getstate()
1607 try:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001608 # Note our initial start point.
1609 decoder.setstate((b'', dec_flags))
1610 start_pos = position
1611 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001612 need_eof = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001613
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001614 # Feed the decoder one byte at a time. As we go, note the
1615 # nearest "safe start point" before the current location
1616 # (a point where the decoder has nothing buffered, so seek()
1617 # can safely start from there and advance to this location).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001618 next_byte = bytearray(1)
1619 for next_byte[0] in next_input:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001620 bytes_fed += 1
1621 chars_decoded += len(decoder.decode(next_byte))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001622 dec_buffer, dec_flags = decoder.getstate()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001623 if not dec_buffer and chars_decoded <= chars_to_skip:
1624 # Decoder buffer is empty, so this is a safe start point.
1625 start_pos += bytes_fed
1626 chars_to_skip -= chars_decoded
1627 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1628 if chars_decoded >= chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001629 break
1630 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001631 # We didn't get enough decoded data; signal EOF to get more.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001632 chars_decoded += len(decoder.decode(b'', final=True))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001633 need_eof = 1
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001634 if chars_decoded < chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001635 raise IOError("can't reconstruct logical file position")
1636
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001637 # The returned cookie corresponds to the last safe start point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001638 return self._pack_cookie(
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001639 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001640 finally:
1641 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001642
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001643 def truncate(self, pos=None):
1644 self.flush()
1645 if pos is None:
1646 pos = self.tell()
1647 self.seek(pos)
1648 return self.buffer.truncate()
1649
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001650 def seek(self, cookie, whence=0):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001651 if self.closed:
1652 raise ValueError("tell on closed file")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001653 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001654 raise IOError("underlying stream is not seekable")
1655 if whence == 1: # seek relative to current position
1656 if cookie != 0:
1657 raise IOError("can't do nonzero cur-relative seeks")
1658 # Seeking to the current position should attempt to
1659 # sync the underlying buffer with the current position.
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001660 whence = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001661 cookie = self.tell()
1662 if whence == 2: # seek relative to end of file
1663 if cookie != 0:
1664 raise IOError("can't do nonzero end-relative seeks")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001665 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001666 position = self.buffer.seek(0, 2)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001667 self._set_decoded_chars('')
1668 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001669 if self._decoder:
1670 self._decoder.reset()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001671 return position
Guido van Rossum9b76da62007-04-11 01:09:03 +00001672 if whence != 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001673 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
Guido van Rossum9b76da62007-04-11 01:09:03 +00001674 (whence,))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001675 if cookie < 0:
1676 raise ValueError("negative seek position %r" % (cookie,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001677 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001678
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001679 # The strategy of seek() is to go back to the safe start point
1680 # and replay the effect of read(chars_to_skip) from there.
1681 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001682 self._unpack_cookie(cookie)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001683
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001684 # Seek back to the safe start point.
1685 self.buffer.seek(start_pos)
1686 self._set_decoded_chars('')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001687 self._snapshot = None
1688
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001689 # Restore the decoder to its state from the safe start point.
1690 if self._decoder or dec_flags or chars_to_skip:
1691 self._decoder = self._decoder or self._get_decoder()
1692 self._decoder.setstate((b'', dec_flags))
1693 self._snapshot = (dec_flags, b'')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001694
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001695 if chars_to_skip:
1696 # Just like _read_chunk, feed the decoder and save a snapshot.
1697 input_chunk = self.buffer.read(bytes_to_feed)
1698 self._set_decoded_chars(
1699 self._decoder.decode(input_chunk, need_eof))
1700 self._snapshot = (dec_flags, input_chunk)
1701
1702 # Skip chars_to_skip of the decoded characters.
1703 if len(self._decoded_chars) < chars_to_skip:
1704 raise IOError("can't restore logical file position")
1705 self._decoded_chars_used = chars_to_skip
1706
1707 return cookie
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001708
Guido van Rossum024da5c2007-05-17 23:59:11 +00001709 def read(self, n=None):
1710 if n is None:
1711 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001712 decoder = self._decoder or self._get_decoder()
Guido van Rossum78892e42007-04-06 17:31:18 +00001713 if n < 0:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001714 # Read everything.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001715 result = (self._get_decoded_chars() +
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001716 decoder.decode(self.buffer.read(), final=True))
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001717 self._set_decoded_chars('')
1718 self._snapshot = None
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001719 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001720 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001721 # Keep reading chunks until we have n characters to return.
1722 eof = False
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001723 result = self._get_decoded_chars(n)
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001724 while len(result) < n and not eof:
1725 eof = not self._read_chunk()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001726 result += self._get_decoded_chars(n - len(result))
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001727 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001728
Guido van Rossum024da5c2007-05-17 23:59:11 +00001729 def __next__(self):
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001730 self._telling = False
1731 line = self.readline()
1732 if not line:
1733 self._snapshot = None
1734 self._telling = self._seekable
1735 raise StopIteration
1736 return line
1737
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001738 def readline(self, limit=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001739 if self.closed:
1740 raise ValueError("read from closed file")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001741 if limit is None:
1742 limit = -1
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001743
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001744 # Grab all the decoded text (we will rewind any extra bits later).
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001745 line = self._get_decoded_chars()
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001746
Guido van Rossum78892e42007-04-06 17:31:18 +00001747 start = 0
1748 decoder = self._decoder or self._get_decoder()
1749
Guido van Rossum8358db22007-08-18 21:39:55 +00001750 pos = endpos = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001751 while True:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001752 if self._readtranslate:
1753 # Newlines are already translated, only search for \n
1754 pos = line.find('\n', start)
1755 if pos >= 0:
1756 endpos = pos + 1
1757 break
1758 else:
1759 start = len(line)
1760
1761 elif self._readuniversal:
Guido van Rossum8358db22007-08-18 21:39:55 +00001762 # Universal newline search. Find any of \r, \r\n, \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001763 # The decoder ensures that \r\n are not split in two pieces
Guido van Rossum78892e42007-04-06 17:31:18 +00001764
Guido van Rossum8358db22007-08-18 21:39:55 +00001765 # In C we'd look for these in parallel of course.
1766 nlpos = line.find("\n", start)
1767 crpos = line.find("\r", start)
1768 if crpos == -1:
1769 if nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001770 # Nothing found
Guido van Rossum8358db22007-08-18 21:39:55 +00001771 start = len(line)
Guido van Rossum78892e42007-04-06 17:31:18 +00001772 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001773 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001774 endpos = nlpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001775 break
1776 elif nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001777 # Found lone \r
1778 endpos = crpos + 1
1779 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001780 elif nlpos < crpos:
1781 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001782 endpos = nlpos + 1
Guido van Rossum78892e42007-04-06 17:31:18 +00001783 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001784 elif nlpos == crpos + 1:
1785 # Found \r\n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001786 endpos = crpos + 2
Guido van Rossum8358db22007-08-18 21:39:55 +00001787 break
1788 else:
1789 # Found \r
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001790 endpos = crpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001791 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001792 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001793 # non-universal
1794 pos = line.find(self._readnl)
1795 if pos >= 0:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001796 endpos = pos + len(self._readnl)
Guido van Rossum8358db22007-08-18 21:39:55 +00001797 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001798
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001799 if limit >= 0 and len(line) >= limit:
1800 endpos = limit # reached length limit
1801 break
1802
Guido van Rossum78892e42007-04-06 17:31:18 +00001803 # No line ending seen yet - get more data
Guido van Rossum8358db22007-08-18 21:39:55 +00001804 more_line = ''
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001805 while self._read_chunk():
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001806 if self._decoded_chars:
Guido van Rossum78892e42007-04-06 17:31:18 +00001807 break
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001808 if self._decoded_chars:
1809 line += self._get_decoded_chars()
Guido van Rossum8358db22007-08-18 21:39:55 +00001810 else:
1811 # end of file
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001812 self._set_decoded_chars('')
1813 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001814 return line
Guido van Rossum78892e42007-04-06 17:31:18 +00001815
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001816 if limit >= 0 and endpos > limit:
1817 endpos = limit # don't exceed limit
1818
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001819 # Rewind _decoded_chars to just after the line ending we found.
1820 self._rewind_decoded_chars(len(line) - endpos)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001821 return line[:endpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001822
Guido van Rossum8358db22007-08-18 21:39:55 +00001823 @property
1824 def newlines(self):
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001825 return self._decoder.newlines if self._decoder else None
Guido van Rossum024da5c2007-05-17 23:59:11 +00001826
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001827class _StringIO(TextIOWrapper):
1828 """Text I/O implementation using an in-memory buffer.
1829
1830 The initial_value argument sets the value of object. The newline
1831 argument is like the one of TextIOWrapper's constructor.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001832 """
Guido van Rossum024da5c2007-05-17 23:59:11 +00001833
1834 # XXX This is really slow, but fully functional
1835
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001836 def __init__(self, initial_value="", newline="\n"):
1837 super(_StringIO, self).__init__(BytesIO(),
1838 encoding="utf-8",
1839 errors="strict",
1840 newline=newline)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001841 if initial_value:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001842 if not isinstance(initial_value, str):
Guido van Rossum34d19282007-08-09 01:03:29 +00001843 initial_value = str(initial_value)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001844 self.write(initial_value)
1845 self.seek(0)
1846
1847 def getvalue(self):
Guido van Rossum34d19282007-08-09 01:03:29 +00001848 self.flush()
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001849 return self.buffer.getvalue().decode(self._encoding, self._errors)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001850
1851try:
1852 import _stringio
1853
1854 # This subclass is a reimplementation of the TextIOWrapper
1855 # interface without any of its text decoding facilities. All the
1856 # stored data is manipulated with the efficient
1857 # _stringio._StringIO extension type. Also, the newline decoding
1858 # mechanism of IncrementalNewlineDecoder is reimplemented here for
1859 # efficiency. Doing otherwise, would require us to implement a
1860 # fake decoder which would add an additional and unnecessary layer
1861 # on top of the _StringIO methods.
1862
1863 class StringIO(_stringio._StringIO, TextIOBase):
1864 """Text I/O implementation using an in-memory buffer.
1865
1866 The initial_value argument sets the value of object. The newline
1867 argument is like the one of TextIOWrapper's constructor.
1868 """
1869
1870 _CHUNK_SIZE = 4096
1871
1872 def __init__(self, initial_value="", newline="\n"):
1873 if newline not in (None, "", "\n", "\r", "\r\n"):
1874 raise ValueError("illegal newline value: %r" % (newline,))
1875
1876 self._readuniversal = not newline
1877 self._readtranslate = newline is None
1878 self._readnl = newline
1879 self._writetranslate = newline != ""
1880 self._writenl = newline or os.linesep
1881 self._pending = ""
1882 self._seennl = 0
1883
1884 # Reset the buffer first, in case __init__ is called
1885 # multiple times.
1886 self.truncate(0)
1887 if initial_value is None:
1888 initial_value = ""
1889 self.write(initial_value)
1890 self.seek(0)
1891
1892 @property
1893 def buffer(self):
1894 raise UnsupportedOperation("%s.buffer attribute is unsupported" %
1895 self.__class__.__name__)
1896
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +00001897 # XXX Cruft to support the TextIOWrapper API. This would only
1898 # be meaningful if StringIO supported the buffer attribute.
1899 # Hopefully, a better solution, than adding these pseudo-attributes,
1900 # will be found.
1901 @property
1902 def encoding(self):
1903 return "utf-8"
1904
1905 @property
1906 def errors(self):
1907 return "strict"
1908
1909 @property
1910 def line_buffering(self):
1911 return False
1912
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001913 def _decode_newlines(self, input, final=False):
1914 # decode input (with the eventual \r from a previous pass)
1915 if self._pending:
1916 input = self._pending + input
1917
1918 # retain last \r even when not translating data:
1919 # then readline() is sure to get \r\n in one pass
1920 if input.endswith("\r") and not final:
1921 input = input[:-1]
1922 self._pending = "\r"
1923 else:
1924 self._pending = ""
1925
1926 # Record which newlines are read
1927 crlf = input.count('\r\n')
1928 cr = input.count('\r') - crlf
1929 lf = input.count('\n') - crlf
1930 self._seennl |= (lf and self._LF) | (cr and self._CR) \
1931 | (crlf and self._CRLF)
1932
1933 if self._readtranslate:
1934 if crlf:
1935 output = input.replace("\r\n", "\n")
1936 if cr:
1937 output = input.replace("\r", "\n")
1938 else:
1939 output = input
1940
1941 return output
1942
1943 def writable(self):
1944 return True
1945
1946 def readable(self):
1947 return True
1948
1949 def seekable(self):
1950 return True
1951
1952 _read = _stringio._StringIO.read
1953 _write = _stringio._StringIO.write
1954 _tell = _stringio._StringIO.tell
1955 _seek = _stringio._StringIO.seek
1956 _truncate = _stringio._StringIO.truncate
1957 _getvalue = _stringio._StringIO.getvalue
1958
1959 def getvalue(self) -> str:
1960 """Retrieve the entire contents of the object."""
1961 if self.closed:
1962 raise ValueError("read on closed file")
1963 return self._getvalue()
1964
1965 def write(self, s: str) -> int:
1966 """Write string s to file.
1967
1968 Returns the number of characters written.
1969 """
1970 if self.closed:
1971 raise ValueError("write to closed file")
1972 if not isinstance(s, str):
1973 raise TypeError("can't write %s to text stream" %
1974 s.__class__.__name__)
1975 length = len(s)
1976 if self._writetranslate and self._writenl != "\n":
1977 s = s.replace("\n", self._writenl)
1978 self._pending = ""
1979 self._write(s)
1980 return length
1981
1982 def read(self, n: int = None) -> str:
1983 """Read at most n characters, returned as a string.
1984
1985 If the argument is negative or omitted, read until EOF
1986 is reached. Return an empty string at EOF.
1987 """
1988 if self.closed:
1989 raise ValueError("read to closed file")
1990 if n is None:
1991 n = -1
1992 res = self._pending
1993 if n < 0:
1994 res += self._decode_newlines(self._read(), True)
1995 self._pending = ""
1996 return res
1997 else:
1998 res = self._decode_newlines(self._read(n), True)
1999 self._pending = res[n:]
2000 return res[:n]
2001
2002 def tell(self) -> int:
2003 """Tell the current file position."""
2004 if self.closed:
2005 raise ValueError("tell from closed file")
2006 if self._pending:
2007 return self._tell() - len(self._pending)
2008 else:
2009 return self._tell()
2010
2011 def seek(self, pos: int = None, whence: int = 0) -> int:
2012 """Change stream position.
2013
2014 Seek to character offset pos relative to position indicated by whence:
2015 0 Start of stream (the default). pos should be >= 0;
2016 1 Current position - pos must be 0;
2017 2 End of stream - pos must be 0.
2018 Returns the new absolute position.
2019 """
2020 if self.closed:
2021 raise ValueError("seek from closed file")
2022 self._pending = ""
2023 return self._seek(pos, whence)
2024
2025 def truncate(self, pos: int = None) -> int:
2026 """Truncate size to pos.
2027
2028 The pos argument defaults to the current file position, as
2029 returned by tell(). Imply an absolute seek to pos.
2030 Returns the new absolute position.
2031 """
2032 if self.closed:
2033 raise ValueError("truncate from closed file")
2034 self._pending = ""
2035 return self._truncate(pos)
2036
2037 def readline(self, limit: int = None) -> str:
2038 if self.closed:
2039 raise ValueError("read from closed file")
2040 if limit is None:
2041 limit = -1
2042 if limit >= 0:
2043 # XXX: Hack to support limit argument, for backwards
2044 # XXX compatibility
2045 line = self.readline()
2046 if len(line) <= limit:
2047 return line
2048 line, self._pending = line[:limit], line[limit:] + self._pending
2049 return line
2050
2051 line = self._pending
2052 self._pending = ""
2053
2054 start = 0
2055 pos = endpos = None
2056 while True:
2057 if self._readtranslate:
2058 # Newlines are already translated, only search for \n
2059 pos = line.find('\n', start)
2060 if pos >= 0:
2061 endpos = pos + 1
2062 break
2063 else:
2064 start = len(line)
2065
2066 elif self._readuniversal:
2067 # Universal newline search. Find any of \r, \r\n, \n
2068 # The decoder ensures that \r\n are not split in two pieces
2069
2070 # In C we'd look for these in parallel of course.
2071 nlpos = line.find("\n", start)
2072 crpos = line.find("\r", start)
2073 if crpos == -1:
2074 if nlpos == -1:
2075 # Nothing found
2076 start = len(line)
2077 else:
2078 # Found \n
2079 endpos = nlpos + 1
2080 break
2081 elif nlpos == -1:
2082 # Found lone \r
2083 endpos = crpos + 1
2084 break
2085 elif nlpos < crpos:
2086 # Found \n
2087 endpos = nlpos + 1
2088 break
2089 elif nlpos == crpos + 1:
2090 # Found \r\n
2091 endpos = crpos + 2
2092 break
2093 else:
2094 # Found \r
2095 endpos = crpos + 1
2096 break
2097 else:
2098 # non-universal
2099 pos = line.find(self._readnl)
2100 if pos >= 0:
2101 endpos = pos + len(self._readnl)
2102 break
2103
2104 # No line ending seen yet - get more data
2105 more_line = self.read(self._CHUNK_SIZE)
2106 if more_line:
2107 line += more_line
2108 else:
2109 # end of file
2110 return line
2111
2112 self._pending = line[endpos:]
2113 return line[:endpos]
2114
2115 _LF = 1
2116 _CR = 2
2117 _CRLF = 4
2118
2119 @property
2120 def newlines(self):
2121 return (None,
2122 "\n",
2123 "\r",
2124 ("\r", "\n"),
2125 "\r\n",
2126 ("\n", "\r\n"),
2127 ("\r", "\r\n"),
2128 ("\r", "\n", "\r\n")
2129 )[self._seennl]
2130
2131
2132except ImportError:
2133 StringIO = _StringIO