blob: 8e65a10e3a4a4f8b3decf07f578e9595ff611f02 [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 codecs
Guido van Rossum141f7672007-04-10 00:22:16 +000061import _fileio
Christian Heimesdeb75f52008-08-15 18:43:03 +000062# Import _thread instead of threading to reduce startup cost
63try:
64 from _thread import allocate_lock as Lock
65except ImportError:
66 from _dummy_thread import allocate_lock as Lock
67
Guido van Rossum28524c72007-02-27 05:47:44 +000068
Guido van Rossum5abbf752007-08-27 17:39:33 +000069# open() uses st_blksize whenever we can
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000070DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
Guido van Rossum01a27522007-03-07 01:00:12 +000071
72
Guido van Rossum141f7672007-04-10 00:22:16 +000073class BlockingIOError(IOError):
Guido van Rossum78892e42007-04-06 17:31:18 +000074
Guido van Rossum141f7672007-04-10 00:22:16 +000075 """Exception raised when I/O would block on a non-blocking I/O stream."""
76
77 def __init__(self, errno, strerror, characters_written=0):
Guido van Rossum01a27522007-03-07 01:00:12 +000078 IOError.__init__(self, errno, strerror)
79 self.characters_written = characters_written
80
Guido van Rossum68bbcd22007-02-27 17:19:33 +000081
Guido van Rossume7fc50f2007-12-03 22:54:21 +000082def open(file, mode="r", buffering=None, encoding=None, errors=None,
83 newline=None, closefd=True):
Christian Heimes5d8da202008-05-06 13:58:24 +000084
Guido van Rossumf0af3e32008-10-02 18:55:37 +000085 r"""Open file and return a stream. Raise IOError upon failure.
Guido van Rossum17e43e52007-02-27 15:45:13 +000086
Guido van Rossumf0af3e32008-10-02 18:55:37 +000087 file is either a text or byte string giving the name (and the path
88 if the file isn't in the current working directory) of the file to
89 be opened or an integer file descriptor of the file to be
90 wrapped. (If a file descriptor is given, it is closed when the
91 returned I/O object is closed, unless closefd is set to False.)
Guido van Rossum8358db22007-08-18 21:39:55 +000092
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000093 mode is an optional string that specifies the mode in which the file
94 is opened. It defaults to 'r' which means open for reading in text
95 mode. Other common values are 'w' for writing (truncating the file if
96 it already exists), and 'a' for appending (which on some Unix systems,
97 means that all writes append to the end of the file regardless of the
98 current seek position). In text mode, if encoding is not specified the
99 encoding used is platform dependent. (For reading and writing raw
100 bytes use binary mode and leave encoding unspecified.) The available
101 modes are:
Guido van Rossum8358db22007-08-18 21:39:55 +0000102
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000103 ========= ===============================================================
104 Character Meaning
105 --------- ---------------------------------------------------------------
106 'r' open for reading (default)
107 'w' open for writing, truncating the file first
108 'a' open for writing, appending to the end of the file if it exists
109 'b' binary mode
110 't' text mode (default)
111 '+' open a disk file for updating (reading and writing)
112 'U' universal newline mode (for backwards compatibility; unneeded
113 for new code)
114 ========= ===============================================================
Guido van Rossum17e43e52007-02-27 15:45:13 +0000115
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000116 The default mode is 'rt' (open for reading text). For binary random
117 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
118 'r+b' opens the file without truncation.
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000119
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000120 Python distinguishes between files opened in binary and text modes,
121 even when the underlying operating system doesn't. Files opened in
122 binary mode (appending 'b' to the mode argument) return contents as
123 bytes objects without any decoding. In text mode (the default, or when
124 't' is appended to the mode argument), the contents of the file are
125 returned as strings, the bytes having been first decoded using a
126 platform-dependent encoding or using the specified encoding if given.
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000127
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000128 buffering is an optional integer used to set the buffering policy. By
129 default full buffering is on. Pass 0 to switch buffering off (only
130 allowed in binary mode), 1 to set line buffering, and an integer > 1
131 for full buffering.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000132
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000133 encoding is the name of the encoding used to decode or encode the
134 file. This should only be used in text mode. The default encoding is
135 platform dependent, but any encoding supported by Python can be
136 passed. See the codecs module for the list of supported encodings.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000137
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000138 errors is an optional string that specifies how encoding errors are to
139 be handled---this argument should not be used in binary mode. Pass
140 'strict' to raise a ValueError exception if there is an encoding error
141 (the default of None has the same effect), or pass 'ignore' to ignore
142 errors. (Note that ignoring encoding errors can lead to data loss.)
143 See the documentation for codecs.register for a list of the permitted
144 encoding error strings.
145
146 newline controls how universal newlines works (it only applies to text
147 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
148 follows:
149
150 * On input, if newline is None, universal newlines mode is
151 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
152 these are translated into '\n' before being returned to the
153 caller. If it is '', universal newline mode is enabled, but line
154 endings are returned to the caller untranslated. If it has any of
155 the other legal values, input lines are only terminated by the given
156 string, and the line ending is returned to the caller untranslated.
157
158 * On output, if newline is None, any '\n' characters written are
159 translated to the system default line separator, os.linesep. If
160 newline is '', no translation takes place. If newline is any of the
161 other legal values, any '\n' characters written are translated to
162 the given string.
163
164 If closefd is False, the underlying file descriptor will be kept open
165 when the file is closed. This does not work when a file name is given
166 and must be True in that case.
167
168 open() returns a file object whose type depends on the mode, and
169 through which the standard file operations such as reading and writing
170 are performed. When open() is used to open a file in a text mode ('w',
171 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
172 a file in a binary mode, the returned class varies: in read binary
173 mode, it returns a BufferedReader; in write binary and append binary
174 modes, it returns a BufferedWriter, and in read/write mode, it returns
175 a BufferedRandom.
176
177 It is also possible to use a string or bytearray as a file for both
178 reading and writing. For strings StringIO can be used like a file
179 opened in a text mode, and for bytes a BytesIO can be used like a file
180 opened in a binary mode.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000181 """
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000182 if not isinstance(file, (str, bytes, int)):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000183 raise TypeError("invalid file: %r" % file)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000184 if not isinstance(mode, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000185 raise TypeError("invalid mode: %r" % mode)
186 if buffering is not None and not isinstance(buffering, int):
187 raise TypeError("invalid buffering: %r" % buffering)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000188 if encoding is not None and not isinstance(encoding, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000189 raise TypeError("invalid encoding: %r" % encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000190 if errors is not None and not isinstance(errors, str):
191 raise TypeError("invalid errors: %r" % errors)
Guido van Rossum28524c72007-02-27 05:47:44 +0000192 modes = set(mode)
Guido van Rossum9be55972007-04-07 02:59:27 +0000193 if modes - set("arwb+tU") or len(mode) > len(modes):
Guido van Rossum28524c72007-02-27 05:47:44 +0000194 raise ValueError("invalid mode: %r" % mode)
195 reading = "r" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000196 writing = "w" in modes
Guido van Rossum28524c72007-02-27 05:47:44 +0000197 appending = "a" in modes
198 updating = "+" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000199 text = "t" in modes
200 binary = "b" in modes
Guido van Rossum7165cb12007-07-10 06:54:34 +0000201 if "U" in modes:
202 if writing or appending:
203 raise ValueError("can't use U and writing mode at once")
Guido van Rossum9be55972007-04-07 02:59:27 +0000204 reading = True
Guido van Rossum28524c72007-02-27 05:47:44 +0000205 if text and binary:
206 raise ValueError("can't have text and binary mode at once")
207 if reading + writing + appending > 1:
208 raise ValueError("can't have read/write/append mode at once")
209 if not (reading or writing or appending):
210 raise ValueError("must have exactly one of read/write/append mode")
211 if binary and encoding is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +0000212 raise ValueError("binary mode doesn't take an encoding argument")
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000213 if binary and errors is not None:
214 raise ValueError("binary mode doesn't take an errors argument")
Guido van Rossum9b76da62007-04-11 01:09:03 +0000215 if binary and newline is not None:
216 raise ValueError("binary mode doesn't take a newline argument")
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000217 raw = FileIO(file,
Guido van Rossum28524c72007-02-27 05:47:44 +0000218 (reading and "r" or "") +
219 (writing and "w" or "") +
220 (appending and "a" or "") +
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000221 (updating and "+" or ""),
222 closefd)
Guido van Rossum28524c72007-02-27 05:47:44 +0000223 if buffering is None:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000224 buffering = -1
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000225 line_buffering = False
226 if buffering == 1 or buffering < 0 and raw.isatty():
227 buffering = -1
228 line_buffering = True
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000229 if buffering < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000230 buffering = DEFAULT_BUFFER_SIZE
Guido van Rossum17e43e52007-02-27 15:45:13 +0000231 try:
232 bs = os.fstat(raw.fileno()).st_blksize
233 except (os.error, AttributeError):
Guido van Rossumbb09b212007-03-18 03:36:28 +0000234 pass
235 else:
Guido van Rossum17e43e52007-02-27 15:45:13 +0000236 if bs > 1:
237 buffering = bs
Guido van Rossum28524c72007-02-27 05:47:44 +0000238 if buffering < 0:
239 raise ValueError("invalid buffering size")
240 if buffering == 0:
241 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000242 raw._name = file
243 raw._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000244 return raw
245 raise ValueError("can't have unbuffered text I/O")
246 if updating:
247 buffer = BufferedRandom(raw, buffering)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000248 elif writing or appending:
Guido van Rossum28524c72007-02-27 05:47:44 +0000249 buffer = BufferedWriter(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000250 elif reading:
Guido van Rossum28524c72007-02-27 05:47:44 +0000251 buffer = BufferedReader(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000252 else:
253 raise ValueError("unknown mode: %r" % mode)
Guido van Rossum28524c72007-02-27 05:47:44 +0000254 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000255 buffer.name = file
256 buffer.mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000257 return buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000258 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000259 text.name = file
260 text.mode = mode
261 return text
Guido van Rossum28524c72007-02-27 05:47:44 +0000262
Christian Heimesa33eb062007-12-08 17:47:40 +0000263class _DocDescriptor:
264 """Helper for builtins.open.__doc__
265 """
266 def __get__(self, obj, typ):
267 return (
268 "open(file, mode='r', buffering=None, encoding=None, "
269 "errors=None, newline=None, closefd=True)\n\n" +
270 open.__doc__)
Guido van Rossum28524c72007-02-27 05:47:44 +0000271
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000272class OpenWrapper:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000273 """Wrapper for builtins.open
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000274
275 Trick so that open won't become a bound method when stored
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000276 as a class variable (as dbm.dumb does).
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000277
278 See initstdio() in Python/pythonrun.c.
279 """
Christian Heimesa33eb062007-12-08 17:47:40 +0000280 __doc__ = _DocDescriptor()
281
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000282 def __new__(cls, *args, **kwargs):
283 return open(*args, **kwargs)
284
285
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000286class UnsupportedOperation(ValueError, IOError):
287 pass
288
289
Guido van Rossumb7f136e2007-08-22 18:14:10 +0000290class IOBase(metaclass=abc.ABCMeta):
Guido van Rossum28524c72007-02-27 05:47:44 +0000291
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000292 """The abstract base class for all I/O classes, acting on streams of
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000293 bytes. There is no public constructor.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000294
Guido van Rossum141f7672007-04-10 00:22:16 +0000295 This class provides dummy implementations for many methods that
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000296 derived classes can override selectively; the default implementations
297 represent a file that cannot be read, written or seeked.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000298
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000299 Even though IOBase does not declare read, readinto, or write because
300 their signatures will vary, implementations and clients should
301 consider those methods part of the interface. Also, implementations
302 may raise a IOError when operations they do not support are called.
Guido van Rossum53807da2007-04-10 19:01:47 +0000303
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000304 The basic type used for binary data read from or written to a file is
305 bytes. bytearrays are accepted too, and in some cases (such as
306 readinto) needed. Text I/O classes work with str data.
307
308 Note that calling any method (even inquiries) on a closed stream is
Benjamin Peterson9a89e962008-04-06 16:47:13 +0000309 undefined. Implementations may raise IOError in this case.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000310
311 IOBase (and its subclasses) support the iterator protocol, meaning
312 that an IOBase object can be iterated over yielding the lines in a
313 stream.
314
315 IOBase also supports the :keyword:`with` statement. In this example,
316 fp is closed after the suite of the with statment is complete:
317
318 with open('spam.txt', 'r') as fp:
319 fp.write('Spam and eggs!')
Guido van Rossum17e43e52007-02-27 15:45:13 +0000320 """
321
Guido van Rossum141f7672007-04-10 00:22:16 +0000322 ### Internal ###
323
324 def _unsupported(self, name: str) -> IOError:
325 """Internal: raise an exception for unsupported operations."""
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000326 raise UnsupportedOperation("%s.%s() not supported" %
327 (self.__class__.__name__, name))
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000328
Guido van Rossum141f7672007-04-10 00:22:16 +0000329 ### Positioning ###
330
Guido van Rossum53807da2007-04-10 19:01:47 +0000331 def seek(self, pos: int, whence: int = 0) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000332 """Change stream position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000333
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000334 Change the stream position to byte offset offset. offset is
335 interpreted relative to the position indicated by whence. Values
336 for whence are:
337
338 * 0 -- start of stream (the default); offset should be zero or positive
339 * 1 -- current stream position; offset may be negative
340 * 2 -- end of stream; offset is usually negative
341
342 Return the new absolute position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000343 """
344 self._unsupported("seek")
345
346 def tell(self) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000347 """Return current stream position."""
Guido van Rossum53807da2007-04-10 19:01:47 +0000348 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000349
Guido van Rossum87429772007-04-10 21:06:59 +0000350 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000351 """Truncate file to size bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000352
Christian Heimes5d8da202008-05-06 13:58:24 +0000353 Size defaults to the current IO position as reported by tell(). Return
354 the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000355 """
356 self._unsupported("truncate")
357
358 ### Flush and close ###
359
360 def flush(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000361 """Flush write buffers, if applicable.
Guido van Rossum141f7672007-04-10 00:22:16 +0000362
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000363 This is not implemented for read-only and non-blocking streams.
Guido van Rossum141f7672007-04-10 00:22:16 +0000364 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000365 # XXX Should this return the number of bytes written???
Guido van Rossum141f7672007-04-10 00:22:16 +0000366
367 __closed = False
368
369 def close(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000370 """Flush and close the IO object.
Guido van Rossum141f7672007-04-10 00:22:16 +0000371
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000372 This method has no effect if the file is already closed.
Guido van Rossum141f7672007-04-10 00:22:16 +0000373 """
374 if not self.__closed:
Guido van Rossum469734b2007-07-10 12:00:45 +0000375 try:
376 self.flush()
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000377 except IOError:
378 pass # If flush() fails, just give up
379 self.__closed = True
Guido van Rossum141f7672007-04-10 00:22:16 +0000380
381 def __del__(self) -> None:
382 """Destructor. Calls close()."""
383 # The try/except block is in case this is called at program
384 # exit time, when it's possible that globals have already been
385 # deleted, and then the close() call might fail. Since
386 # there's nothing we can do about such failures and they annoy
387 # the end users, we suppress the traceback.
388 try:
389 self.close()
390 except:
391 pass
392
393 ### Inquiries ###
394
395 def seekable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000396 """Return whether object supports random access.
Guido van Rossum141f7672007-04-10 00:22:16 +0000397
398 If False, seek(), tell() and truncate() will raise IOError.
399 This method may need to do a test seek().
400 """
401 return False
402
Guido van Rossum5abbf752007-08-27 17:39:33 +0000403 def _checkSeekable(self, msg=None):
404 """Internal: raise an IOError if file is not seekable
405 """
406 if not self.seekable():
407 raise IOError("File or stream is not seekable."
408 if msg is None else msg)
409
410
Guido van Rossum141f7672007-04-10 00:22:16 +0000411 def readable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000412 """Return whether object was opened for reading.
Guido van Rossum141f7672007-04-10 00:22:16 +0000413
414 If False, read() will raise IOError.
415 """
416 return False
417
Guido van Rossum5abbf752007-08-27 17:39:33 +0000418 def _checkReadable(self, msg=None):
419 """Internal: raise an IOError if file is not readable
420 """
421 if not self.readable():
422 raise IOError("File or stream is not readable."
423 if msg is None else msg)
424
Guido van Rossum141f7672007-04-10 00:22:16 +0000425 def writable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000426 """Return whether object was opened for writing.
Guido van Rossum141f7672007-04-10 00:22:16 +0000427
428 If False, write() and truncate() will raise IOError.
429 """
430 return False
431
Guido van Rossum5abbf752007-08-27 17:39:33 +0000432 def _checkWritable(self, msg=None):
433 """Internal: raise an IOError if file is not writable
434 """
435 if not self.writable():
436 raise IOError("File or stream is not writable."
437 if msg is None else msg)
438
Guido van Rossum141f7672007-04-10 00:22:16 +0000439 @property
440 def closed(self):
441 """closed: bool. True iff the file has been closed.
442
443 For backwards compatibility, this is a property, not a predicate.
444 """
445 return self.__closed
446
Guido van Rossum5abbf752007-08-27 17:39:33 +0000447 def _checkClosed(self, msg=None):
448 """Internal: raise an ValueError if file is closed
449 """
450 if self.closed:
451 raise ValueError("I/O operation on closed file."
452 if msg is None else msg)
453
Guido van Rossum141f7672007-04-10 00:22:16 +0000454 ### Context manager ###
455
456 def __enter__(self) -> "IOBase": # That's a forward reference
457 """Context management protocol. Returns self."""
Christian Heimes3ecfea712008-02-09 20:51:34 +0000458 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000459 return self
460
461 def __exit__(self, *args) -> None:
462 """Context management protocol. Calls close()"""
463 self.close()
464
465 ### Lower-level APIs ###
466
467 # XXX Should these be present even if unimplemented?
468
469 def fileno(self) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000470 """Returns underlying file descriptor if one exists.
Guido van Rossum141f7672007-04-10 00:22:16 +0000471
Christian Heimes5d8da202008-05-06 13:58:24 +0000472 An IOError is raised if the IO object does not use a file descriptor.
Guido van Rossum141f7672007-04-10 00:22:16 +0000473 """
474 self._unsupported("fileno")
475
476 def isatty(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000477 """Return whether this is an 'interactive' stream.
478
479 Return False if it can't be determined.
Guido van Rossum141f7672007-04-10 00:22:16 +0000480 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000481 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000482 return False
483
Guido van Rossum7165cb12007-07-10 06:54:34 +0000484 ### Readline[s] and writelines ###
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000485
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000486 def readline(self, limit: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000487 r"""Read and return a line from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000488
489 If limit is specified, at most limit bytes will be read.
490
491 The line terminator is always b'\n' for binary files; for text
492 files, the newlines argument to open can be used to select the line
493 terminator(s) recognized.
494 """
495 # For backwards compatibility, a (slowish) readline().
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000496 self._checkClosed()
Guido van Rossum2bf71382007-06-08 00:07:57 +0000497 if hasattr(self, "peek"):
498 def nreadahead():
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000499 readahead = self.peek(1)
Guido van Rossum2bf71382007-06-08 00:07:57 +0000500 if not readahead:
501 return 1
502 n = (readahead.find(b"\n") + 1) or len(readahead)
503 if limit >= 0:
504 n = min(n, limit)
505 return n
506 else:
507 def nreadahead():
508 return 1
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000509 if limit is None:
510 limit = -1
Guido van Rossum254348e2007-11-21 19:29:53 +0000511 res = bytearray()
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000512 while limit < 0 or len(res) < limit:
Guido van Rossum2bf71382007-06-08 00:07:57 +0000513 b = self.read(nreadahead())
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000514 if not b:
515 break
516 res += b
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000517 if res.endswith(b"\n"):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000518 break
Guido van Rossum98297ee2007-11-06 21:34:58 +0000519 return bytes(res)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000520
Guido van Rossum7165cb12007-07-10 06:54:34 +0000521 def __iter__(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000522 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000523 return self
524
525 def __next__(self):
526 line = self.readline()
527 if not line:
528 raise StopIteration
529 return line
530
531 def readlines(self, hint=None):
Christian Heimes5d8da202008-05-06 13:58:24 +0000532 """Return a list of lines from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000533
534 hint can be specified to control the number of lines read: no more
535 lines will be read if the total size (in bytes/characters) of all
536 lines so far exceeds hint.
537 """
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000538 if hint is None or hint <= 0:
Guido van Rossum7165cb12007-07-10 06:54:34 +0000539 return list(self)
540 n = 0
541 lines = []
542 for line in self:
543 lines.append(line)
544 n += len(line)
545 if n >= hint:
546 break
547 return lines
548
549 def writelines(self, lines):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000550 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000551 for line in lines:
552 self.write(line)
553
Guido van Rossum141f7672007-04-10 00:22:16 +0000554
555class RawIOBase(IOBase):
556
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000557 """Base class for raw binary I/O."""
Guido van Rossum141f7672007-04-10 00:22:16 +0000558
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000559 # The read() method is implemented by calling readinto(); derived
560 # classes that want to support read() only need to implement
561 # readinto() as a primitive operation. In general, readinto() can be
562 # more efficient than read().
Guido van Rossum141f7672007-04-10 00:22:16 +0000563
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000564 # (It would be tempting to also provide an implementation of
565 # readinto() in terms of read(), in case the latter is a more suitable
566 # primitive operation, but that would lead to nasty recursion in case
567 # a subclass doesn't implement either.)
Guido van Rossum141f7672007-04-10 00:22:16 +0000568
Guido van Rossum7165cb12007-07-10 06:54:34 +0000569 def read(self, n: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000570 """Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000571
Georg Brandlf91197c2008-04-09 07:33:01 +0000572 Returns an empty bytes object on EOF, or None if the object is
Guido van Rossum01a27522007-03-07 01:00:12 +0000573 set not to block and has no data to read.
574 """
Guido van Rossum7165cb12007-07-10 06:54:34 +0000575 if n is None:
576 n = -1
577 if n < 0:
578 return self.readall()
Guido van Rossum254348e2007-11-21 19:29:53 +0000579 b = bytearray(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000580 n = self.readinto(b)
581 del b[n:]
Guido van Rossum98297ee2007-11-06 21:34:58 +0000582 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000583
Guido van Rossum7165cb12007-07-10 06:54:34 +0000584 def readall(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000585 """Read until EOF, using multiple read() call."""
Guido van Rossum254348e2007-11-21 19:29:53 +0000586 res = bytearray()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000587 while True:
588 data = self.read(DEFAULT_BUFFER_SIZE)
589 if not data:
590 break
591 res += data
Guido van Rossum98297ee2007-11-06 21:34:58 +0000592 return bytes(res)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000593
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000594 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000595 """Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000596
597 Returns number of bytes read (0 for EOF), or None if the object
598 is set not to block as has no data to read.
599 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000600 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000601
Guido van Rossum141f7672007-04-10 00:22:16 +0000602 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000603 """Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000604
Guido van Rossum78892e42007-04-06 17:31:18 +0000605 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000606 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000607 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000608
Guido van Rossum78892e42007-04-06 17:31:18 +0000609
Guido van Rossum141f7672007-04-10 00:22:16 +0000610class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000611
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000612 """Raw I/O implementation for OS files."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000613
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000614 # This multiply inherits from _FileIO and RawIOBase to make
615 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
616 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
617 # to do since _fileio.c is written in C).
Guido van Rossuma9e20242007-03-08 00:43:48 +0000618
Guido van Rossum87429772007-04-10 21:06:59 +0000619 def close(self):
620 _fileio._FileIO.close(self)
621 RawIOBase.close(self)
622
Guido van Rossum13633bb2007-04-13 18:42:35 +0000623 @property
624 def name(self):
625 return self._name
626
Georg Brandlf91197c2008-04-09 07:33:01 +0000627 # XXX(gb): _FileIO already has a mode property
Guido van Rossum13633bb2007-04-13 18:42:35 +0000628 @property
629 def mode(self):
630 return self._mode
631
Guido van Rossuma9e20242007-03-08 00:43:48 +0000632
Guido van Rossumcce92b22007-04-10 14:41:39 +0000633class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000634
635 """Base class for buffered IO objects.
636
637 The main difference with RawIOBase is that the read() method
638 supports omitting the size argument, and does not have a default
639 implementation that defers to readinto().
640
641 In addition, read(), readinto() and write() may raise
642 BlockingIOError if the underlying raw stream is in non-blocking
643 mode and not ready; unlike their raw counterparts, they will never
644 return None.
645
646 A typical implementation should not inherit from a RawIOBase
647 implementation, but wrap one.
648 """
649
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000650 def read(self, n: int = None) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000651 """Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000652
Guido van Rossum024da5c2007-05-17 23:59:11 +0000653 If the argument is omitted, None, or negative, reads and
654 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000655
656 If the argument is positive, and the underlying raw stream is
657 not 'interactive', multiple raw reads may be issued to satisfy
658 the byte count (unless EOF is reached first). But for
659 interactive raw streams (XXX and for pipes?), at most one raw
660 read will be issued, and a short result does not imply that
661 EOF is imminent.
662
663 Returns an empty bytes array on EOF.
664
665 Raises BlockingIOError if the underlying raw stream has no
666 data at the moment.
667 """
668 self._unsupported("read")
669
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000670 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000671 """Read up to len(b) bytes into b.
Guido van Rossum141f7672007-04-10 00:22:16 +0000672
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000673 Like read(), this may issue multiple reads to the underlying raw
674 stream, unless the latter is 'interactive'.
Guido van Rossum141f7672007-04-10 00:22:16 +0000675
676 Returns the number of bytes read (0 for EOF).
677
678 Raises BlockingIOError if the underlying raw stream has no
679 data at the moment.
680 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000681 # XXX This ought to work with anything that supports the buffer API
Guido van Rossum87429772007-04-10 21:06:59 +0000682 data = self.read(len(b))
683 n = len(data)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000684 try:
685 b[:n] = data
686 except TypeError as err:
687 import array
688 if not isinstance(b, array.array):
689 raise err
690 b[:n] = array.array('b', data)
Guido van Rossum87429772007-04-10 21:06:59 +0000691 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000692
693 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000694 """Write the given buffer to the IO stream.
Guido van Rossum141f7672007-04-10 00:22:16 +0000695
Christian Heimes5d8da202008-05-06 13:58:24 +0000696 Return the number of bytes written, which is never less than
Guido van Rossum141f7672007-04-10 00:22:16 +0000697 len(b).
698
699 Raises BlockingIOError if the buffer is full and the
700 underlying raw stream cannot accept more data at the moment.
701 """
702 self._unsupported("write")
703
704
705class _BufferedIOMixin(BufferedIOBase):
706
707 """A mixin implementation of BufferedIOBase with an underlying raw stream.
708
709 This passes most requests on to the underlying raw stream. It
710 does *not* provide implementations of read(), readinto() or
711 write().
712 """
713
714 def __init__(self, raw):
715 self.raw = raw
716
717 ### Positioning ###
718
719 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000720 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000721
722 def tell(self):
723 return self.raw.tell()
724
725 def truncate(self, pos=None):
Guido van Rossum79b79ee2007-10-25 23:21:03 +0000726 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
727 # and a flush may be necessary to synch both views of the current
728 # file state.
729 self.flush()
Guido van Rossum57233cb2007-10-26 17:19:33 +0000730
731 if pos is None:
732 pos = self.tell()
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000733 # XXX: Should seek() be used, instead of passing the position
734 # XXX directly to truncate?
Guido van Rossum57233cb2007-10-26 17:19:33 +0000735 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000736
737 ### Flush and close ###
738
739 def flush(self):
740 self.raw.flush()
741
742 def close(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000743 if not self.closed:
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000744 try:
745 self.flush()
746 except IOError:
747 pass # If flush() fails, just give up
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000748 self.raw.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000749
750 ### Inquiries ###
751
752 def seekable(self):
753 return self.raw.seekable()
754
755 def readable(self):
756 return self.raw.readable()
757
758 def writable(self):
759 return self.raw.writable()
760
761 @property
762 def closed(self):
763 return self.raw.closed
764
765 ### Lower-level APIs ###
766
767 def fileno(self):
768 return self.raw.fileno()
769
770 def isatty(self):
771 return self.raw.isatty()
772
773
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000774class _BytesIO(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000775
Guido van Rossum024da5c2007-05-17 23:59:11 +0000776 """Buffered I/O implementation using an in-memory bytes buffer."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000777
Guido van Rossum024da5c2007-05-17 23:59:11 +0000778 def __init__(self, initial_bytes=None):
Guido van Rossum254348e2007-11-21 19:29:53 +0000779 buf = bytearray()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000780 if initial_bytes is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000781 buf += initial_bytes
782 self._buffer = buf
Guido van Rossum28524c72007-02-27 05:47:44 +0000783 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000784
785 def getvalue(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000786 """Return the bytes value (contents) of the buffer
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000787 """
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000788 if self.closed:
789 raise ValueError("getvalue on closed file")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000790 return bytes(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000791
Guido van Rossum024da5c2007-05-17 23:59:11 +0000792 def read(self, n=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000793 if self.closed:
794 raise ValueError("read from closed file")
Guido van Rossum024da5c2007-05-17 23:59:11 +0000795 if n is None:
796 n = -1
Guido van Rossum141f7672007-04-10 00:22:16 +0000797 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000798 n = len(self._buffer)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000799 if len(self._buffer) <= self._pos:
Alexandre Vassalotti2e0419d2008-05-07 00:09:04 +0000800 return b""
Guido van Rossum28524c72007-02-27 05:47:44 +0000801 newpos = min(len(self._buffer), self._pos + n)
802 b = self._buffer[self._pos : newpos]
803 self._pos = newpos
Guido van Rossum98297ee2007-11-06 21:34:58 +0000804 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000805
Guido van Rossum024da5c2007-05-17 23:59:11 +0000806 def read1(self, n):
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000807 """This is the same as read.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000808 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000809 return self.read(n)
810
Guido van Rossum28524c72007-02-27 05:47:44 +0000811 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000812 if self.closed:
813 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +0000814 if isinstance(b, str):
815 raise TypeError("can't write str to binary stream")
Guido van Rossum28524c72007-02-27 05:47:44 +0000816 n = len(b)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000817 if n == 0:
818 return 0
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000819 pos = self._pos
820 if pos > len(self._buffer):
Guido van Rossumb972a782007-07-21 00:25:15 +0000821 # Inserts null bytes between the current end of the file
822 # and the new write position.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000823 padding = b'\x00' * (pos - len(self._buffer))
824 self._buffer += padding
825 self._buffer[pos:pos + n] = b
826 self._pos += n
Guido van Rossum28524c72007-02-27 05:47:44 +0000827 return n
828
829 def seek(self, pos, whence=0):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000830 if self.closed:
831 raise ValueError("seek on closed file")
Christian Heimes3ab4f652007-11-09 01:27:29 +0000832 try:
833 pos = pos.__index__()
834 except AttributeError as err:
835 raise TypeError("an integer is required") from err
Guido van Rossum28524c72007-02-27 05:47:44 +0000836 if whence == 0:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000837 if pos < 0:
838 raise ValueError("negative seek position %r" % (pos,))
Alexandre Vassalottif0c0ff62008-05-09 21:21:21 +0000839 self._pos = pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000840 elif whence == 1:
841 self._pos = max(0, self._pos + pos)
842 elif whence == 2:
843 self._pos = max(0, len(self._buffer) + pos)
844 else:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000845 raise ValueError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000846 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000847
848 def tell(self):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000849 if self.closed:
850 raise ValueError("tell on closed file")
Guido van Rossum28524c72007-02-27 05:47:44 +0000851 return self._pos
852
853 def truncate(self, pos=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000854 if self.closed:
855 raise ValueError("truncate on closed file")
Guido van Rossum28524c72007-02-27 05:47:44 +0000856 if pos is None:
857 pos = self._pos
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000858 elif pos < 0:
859 raise ValueError("negative truncate position %r" % (pos,))
Guido van Rossum28524c72007-02-27 05:47:44 +0000860 del self._buffer[pos:]
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000861 return self.seek(pos)
Guido van Rossum28524c72007-02-27 05:47:44 +0000862
863 def readable(self):
864 return True
865
866 def writable(self):
867 return True
868
869 def seekable(self):
870 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000871
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000872# Use the faster implementation of BytesIO if available
873try:
874 import _bytesio
875
876 class BytesIO(_bytesio._BytesIO, BufferedIOBase):
877 __doc__ = _bytesio._BytesIO.__doc__
878
879except ImportError:
880 BytesIO = _BytesIO
881
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000882
Guido van Rossum141f7672007-04-10 00:22:16 +0000883class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000884
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000885 """BufferedReader(raw[, buffer_size])
886
887 A buffer for a readable, sequential BaseRawIO object.
888
889 The constructor creates a BufferedReader for the given readable raw
890 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
891 is used.
892 """
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000893
Guido van Rossum78892e42007-04-06 17:31:18 +0000894 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000895 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000896 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000897 raw._checkReadable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000898 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum78892e42007-04-06 17:31:18 +0000899 self.buffer_size = buffer_size
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000900 self._reset_read_buf()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +0000901 self._read_lock = Lock()
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000902
903 def _reset_read_buf(self):
904 self._read_buf = b""
905 self._read_pos = 0
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000906
Guido van Rossum024da5c2007-05-17 23:59:11 +0000907 def read(self, n=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000908 """Read n bytes.
909
910 Returns exactly n bytes of data unless the underlying raw IO
Walter Dörwalda3270002007-05-29 19:13:29 +0000911 stream reaches EOF or if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000912 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000913 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000914 """
Antoine Pitrou87695762008-08-14 22:44:29 +0000915 with self._read_lock:
916 return self._read_unlocked(n)
917
918 def _read_unlocked(self, n=None):
Guido van Rossum78892e42007-04-06 17:31:18 +0000919 nodata_val = b""
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000920 empty_values = (b"", None)
921 buf = self._read_buf
922 pos = self._read_pos
923
924 # Special case for when the number of bytes to read is unspecified.
925 if n is None or n == -1:
926 self._reset_read_buf()
927 chunks = [buf[pos:]] # Strip the consumed bytes.
928 current_size = 0
929 while True:
930 # Read until EOF or until read() would block.
931 chunk = self.raw.read()
932 if chunk in empty_values:
933 nodata_val = chunk
934 break
935 current_size += len(chunk)
936 chunks.append(chunk)
937 return b"".join(chunks) or nodata_val
938
939 # The number of bytes to read is specified, return at most n bytes.
940 avail = len(buf) - pos # Length of the available buffered data.
941 if n <= avail:
942 # Fast path: the data to read is fully buffered.
943 self._read_pos += n
944 return buf[pos:pos+n]
945 # Slow path: read from the stream until enough bytes are read,
946 # or until an EOF occurs or until read() would block.
947 chunks = [buf[pos:]]
948 wanted = max(self.buffer_size, n)
949 while avail < n:
950 chunk = self.raw.read(wanted)
951 if chunk in empty_values:
952 nodata_val = chunk
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000953 break
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000954 avail += len(chunk)
955 chunks.append(chunk)
956 # n is more then avail only when an EOF occurred or when
957 # read() would have blocked.
958 n = min(n, avail)
959 out = b"".join(chunks)
960 self._read_buf = out[n:] # Save the extra data in the buffer.
961 self._read_pos = 0
962 return out[:n] if out else nodata_val
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000963
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000964 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000965 """Returns buffered bytes without advancing the position.
966
967 The argument indicates a desired minimal number of bytes; we
968 do at most one raw read to satisfy it. We never return more
969 than self.buffer_size.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000970 """
Antoine Pitrou87695762008-08-14 22:44:29 +0000971 with self._read_lock:
972 return self._peek_unlocked(n)
973
974 def _peek_unlocked(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000975 want = min(n, self.buffer_size)
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000976 have = len(self._read_buf) - self._read_pos
Guido van Rossum13633bb2007-04-13 18:42:35 +0000977 if have < want:
978 to_read = self.buffer_size - have
979 current = self.raw.read(to_read)
980 if current:
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000981 self._read_buf = self._read_buf[self._read_pos:] + current
982 self._read_pos = 0
983 return self._read_buf[self._read_pos:]
Guido van Rossum13633bb2007-04-13 18:42:35 +0000984
985 def read1(self, n):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000986 """Reads up to n bytes, with at most one read() system call."""
987 # Returns up to n bytes. If at least one byte is buffered, we
988 # only return buffered bytes. Otherwise, we do one raw read.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000989 if n <= 0:
990 return b""
Antoine Pitrou87695762008-08-14 22:44:29 +0000991 with self._read_lock:
992 self._peek_unlocked(1)
993 return self._read_unlocked(
994 min(n, len(self._read_buf) - self._read_pos))
Guido van Rossum13633bb2007-04-13 18:42:35 +0000995
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000996 def tell(self):
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000997 return self.raw.tell() - len(self._read_buf) + self._read_pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000998
999 def seek(self, pos, whence=0):
Antoine Pitrou87695762008-08-14 22:44:29 +00001000 with self._read_lock:
1001 if whence == 1:
1002 pos -= len(self._read_buf) - self._read_pos
1003 pos = self.raw.seek(pos, whence)
1004 self._reset_read_buf()
1005 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001006
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001007
Guido van Rossum141f7672007-04-10 00:22:16 +00001008class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001009
Christian Heimes5d8da202008-05-06 13:58:24 +00001010 """A buffer for a writeable sequential RawIO object.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001011
1012 The constructor creates a BufferedWriter for the given writeable raw
1013 stream. If the buffer_size is not given, it defaults to
1014 DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
1015 twice the buffer size.
1016 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001017
Guido van Rossum141f7672007-04-10 00:22:16 +00001018 def __init__(self, raw,
1019 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001020 raw._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001021 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001022 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +00001023 self.max_buffer_size = (2*buffer_size
1024 if max_buffer_size is None
1025 else max_buffer_size)
Guido van Rossum254348e2007-11-21 19:29:53 +00001026 self._write_buf = bytearray()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +00001027 self._write_lock = Lock()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001028
1029 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001030 if self.closed:
1031 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +00001032 if isinstance(b, str):
1033 raise TypeError("can't write str to binary stream")
Antoine Pitrou87695762008-08-14 22:44:29 +00001034 with self._write_lock:
1035 # XXX we can implement some more tricks to try and avoid
1036 # partial writes
1037 if len(self._write_buf) > self.buffer_size:
1038 # We're full, so let's pre-flush the buffer
1039 try:
1040 self._flush_unlocked()
1041 except BlockingIOError as e:
1042 # We can't accept anything else.
1043 # XXX Why not just let the exception pass through?
1044 raise BlockingIOError(e.errno, e.strerror, 0)
1045 before = len(self._write_buf)
1046 self._write_buf.extend(b)
1047 written = len(self._write_buf) - before
1048 if len(self._write_buf) > self.buffer_size:
1049 try:
1050 self._flush_unlocked()
1051 except BlockingIOError as e:
1052 if len(self._write_buf) > self.max_buffer_size:
1053 # We've hit max_buffer_size. We have to accept a
1054 # partial write and cut back our buffer.
1055 overage = len(self._write_buf) - self.max_buffer_size
1056 self._write_buf = self._write_buf[:self.max_buffer_size]
1057 raise BlockingIOError(e.errno, e.strerror, overage)
1058 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001059
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001060 def truncate(self, pos=None):
Antoine Pitrou87695762008-08-14 22:44:29 +00001061 with self._write_lock:
1062 self._flush_unlocked()
1063 if pos is None:
1064 pos = self.raw.tell()
1065 return self.raw.truncate(pos)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001066
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001067 def flush(self):
Antoine Pitrou87695762008-08-14 22:44:29 +00001068 with self._write_lock:
1069 self._flush_unlocked()
1070
1071 def _flush_unlocked(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001072 if self.closed:
1073 raise ValueError("flush of closed file")
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001074 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +00001075 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001076 while self._write_buf:
1077 n = self.raw.write(self._write_buf)
1078 del self._write_buf[:n]
1079 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001080 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001081 n = e.characters_written
1082 del self._write_buf[:n]
1083 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001084 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001085
1086 def tell(self):
1087 return self.raw.tell() + len(self._write_buf)
1088
1089 def seek(self, pos, whence=0):
Antoine Pitrou87695762008-08-14 22:44:29 +00001090 with self._write_lock:
1091 self._flush_unlocked()
1092 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001093
Guido van Rossum01a27522007-03-07 01:00:12 +00001094
Guido van Rossum141f7672007-04-10 00:22:16 +00001095class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001096
Guido van Rossum01a27522007-03-07 01:00:12 +00001097 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001098
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001099 A buffered reader object and buffered writer object put together to
1100 form a sequential IO object that can read and write. This is typically
1101 used with a socket or two-way pipe.
Guido van Rossum78892e42007-04-06 17:31:18 +00001102
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001103 reader and writer are RawIOBase objects that are readable and
1104 writeable respectively. If the buffer_size is omitted it defaults to
1105 DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
1106 defaults to twice the buffer size.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001107 """
1108
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001109 # XXX The usefulness of this (compared to having two separate IO
1110 # objects) is questionable.
1111
Guido van Rossum141f7672007-04-10 00:22:16 +00001112 def __init__(self, reader, writer,
1113 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1114 """Constructor.
1115
1116 The arguments are two RawIO instances.
1117 """
Guido van Rossum5abbf752007-08-27 17:39:33 +00001118 reader._checkReadable()
1119 writer._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001120 self.reader = BufferedReader(reader, buffer_size)
1121 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001122
Guido van Rossum024da5c2007-05-17 23:59:11 +00001123 def read(self, n=None):
1124 if n is None:
1125 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001126 return self.reader.read(n)
1127
Guido van Rossum141f7672007-04-10 00:22:16 +00001128 def readinto(self, b):
1129 return self.reader.readinto(b)
1130
Guido van Rossum01a27522007-03-07 01:00:12 +00001131 def write(self, b):
1132 return self.writer.write(b)
1133
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001134 def peek(self, n=0):
1135 return self.reader.peek(n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001136
1137 def read1(self, n):
1138 return self.reader.read1(n)
1139
Guido van Rossum01a27522007-03-07 01:00:12 +00001140 def readable(self):
1141 return self.reader.readable()
1142
1143 def writable(self):
1144 return self.writer.writable()
1145
1146 def flush(self):
1147 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001148
Guido van Rossum01a27522007-03-07 01:00:12 +00001149 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +00001150 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +00001151 self.reader.close()
1152
1153 def isatty(self):
1154 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +00001155
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001156 @property
1157 def closed(self):
Guido van Rossum141f7672007-04-10 00:22:16 +00001158 return self.writer.closed()
Guido van Rossum01a27522007-03-07 01:00:12 +00001159
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001160
Guido van Rossum141f7672007-04-10 00:22:16 +00001161class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +00001162
Christian Heimes5d8da202008-05-06 13:58:24 +00001163 """A buffered interface to random access streams.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001164
1165 The constructor creates a reader and writer for a seekable stream,
1166 raw, given in the first argument. If the buffer_size is omitted it
1167 defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
1168 writer) defaults to twice the buffer size.
1169 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001170
Guido van Rossum141f7672007-04-10 00:22:16 +00001171 def __init__(self, raw,
1172 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001173 raw._checkSeekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001174 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001175 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1176
Guido van Rossum01a27522007-03-07 01:00:12 +00001177 def seek(self, pos, whence=0):
1178 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001179 # First do the raw seek, then empty the read buffer, so that
1180 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +00001181 pos = self.raw.seek(pos, whence)
Antoine Pitrou87695762008-08-14 22:44:29 +00001182 with self._read_lock:
1183 self._reset_read_buf()
Guido van Rossum53807da2007-04-10 19:01:47 +00001184 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +00001185
1186 def tell(self):
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001187 if self._write_buf:
Guido van Rossum01a27522007-03-07 01:00:12 +00001188 return self.raw.tell() + len(self._write_buf)
1189 else:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001190 return BufferedReader.tell(self)
Guido van Rossum01a27522007-03-07 01:00:12 +00001191
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001192 def truncate(self, pos=None):
1193 if pos is None:
1194 pos = self.tell()
1195 # Use seek to flush the read buffer.
1196 self.seek(pos)
1197 return BufferedWriter.truncate(self)
1198
Guido van Rossum024da5c2007-05-17 23:59:11 +00001199 def read(self, n=None):
1200 if n is None:
1201 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001202 self.flush()
1203 return BufferedReader.read(self, n)
1204
Guido van Rossum141f7672007-04-10 00:22:16 +00001205 def readinto(self, b):
1206 self.flush()
1207 return BufferedReader.readinto(self, b)
1208
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001209 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +00001210 self.flush()
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001211 return BufferedReader.peek(self, n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001212
1213 def read1(self, n):
1214 self.flush()
1215 return BufferedReader.read1(self, n)
1216
Guido van Rossum01a27522007-03-07 01:00:12 +00001217 def write(self, b):
Guido van Rossum78892e42007-04-06 17:31:18 +00001218 if self._read_buf:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001219 # Undo readahead
Antoine Pitrou87695762008-08-14 22:44:29 +00001220 with self._read_lock:
1221 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1222 self._reset_read_buf()
Guido van Rossum01a27522007-03-07 01:00:12 +00001223 return BufferedWriter.write(self, b)
1224
Guido van Rossum78892e42007-04-06 17:31:18 +00001225
Guido van Rossumcce92b22007-04-10 14:41:39 +00001226class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +00001227
1228 """Base class for text I/O.
1229
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001230 This class provides a character and line based interface to stream
1231 I/O. There is no readinto method because Python's character strings
1232 are immutable. There is no public constructor.
Guido van Rossum78892e42007-04-06 17:31:18 +00001233 """
1234
1235 def read(self, n: int = -1) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001236 """Read at most n characters from stream.
Guido van Rossum78892e42007-04-06 17:31:18 +00001237
1238 Read from underlying buffer until we have n characters or we hit EOF.
1239 If n is negative or omitted, read until EOF.
1240 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001241 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +00001242
Guido van Rossum9b76da62007-04-11 01:09:03 +00001243 def write(self, s: str) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001244 """Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001245 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +00001246
Guido van Rossum9b76da62007-04-11 01:09:03 +00001247 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001248 """Truncate size to pos."""
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001249 self._unsupported("truncate")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001250
Guido van Rossum78892e42007-04-06 17:31:18 +00001251 def readline(self) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001252 """Read until newline or EOF.
Guido van Rossum78892e42007-04-06 17:31:18 +00001253
1254 Returns an empty string if EOF is hit immediately.
1255 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001256 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +00001257
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001258 @property
1259 def encoding(self):
1260 """Subclasses should override."""
1261 return None
1262
Guido van Rossum8358db22007-08-18 21:39:55 +00001263 @property
1264 def newlines(self):
Christian Heimes5d8da202008-05-06 13:58:24 +00001265 """Line endings translated so far.
Guido van Rossum8358db22007-08-18 21:39:55 +00001266
1267 Only line endings translated during reading are considered.
1268
1269 Subclasses should override.
1270 """
1271 return None
1272
Guido van Rossum78892e42007-04-06 17:31:18 +00001273
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001274class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001275 r"""Codec used when reading a file in universal newlines mode. It wraps
1276 another incremental decoder, translating \r\n and \r into \n. It also
1277 records the types of newlines encountered. When used with
1278 translate=False, it ensures that the newline sequence is returned in
1279 one piece.
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001280 """
1281 def __init__(self, decoder, translate, errors='strict'):
1282 codecs.IncrementalDecoder.__init__(self, errors=errors)
1283 self.buffer = b''
1284 self.translate = translate
1285 self.decoder = decoder
1286 self.seennl = 0
1287
1288 def decode(self, input, final=False):
1289 # decode input (with the eventual \r from a previous pass)
1290 if self.buffer:
1291 input = self.buffer + input
1292
1293 output = self.decoder.decode(input, final=final)
1294
1295 # retain last \r even when not translating data:
1296 # then readline() is sure to get \r\n in one pass
1297 if output.endswith("\r") and not final:
1298 output = output[:-1]
1299 self.buffer = b'\r'
1300 else:
1301 self.buffer = b''
1302
1303 # Record which newlines are read
1304 crlf = output.count('\r\n')
1305 cr = output.count('\r') - crlf
1306 lf = output.count('\n') - crlf
1307 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1308 | (crlf and self._CRLF)
1309
1310 if self.translate:
1311 if crlf:
1312 output = output.replace("\r\n", "\n")
1313 if cr:
1314 output = output.replace("\r", "\n")
1315
1316 return output
1317
1318 def getstate(self):
1319 buf, flag = self.decoder.getstate()
1320 return buf + self.buffer, flag
1321
1322 def setstate(self, state):
1323 buf, flag = state
1324 if buf.endswith(b'\r'):
1325 self.buffer = b'\r'
1326 buf = buf[:-1]
1327 else:
1328 self.buffer = b''
1329 self.decoder.setstate((buf, flag))
1330
1331 def reset(self):
Alexandre Vassalottic3d7fe02007-12-28 01:24:22 +00001332 self.seennl = 0
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001333 self.buffer = b''
1334 self.decoder.reset()
1335
1336 _LF = 1
1337 _CR = 2
1338 _CRLF = 4
1339
1340 @property
1341 def newlines(self):
1342 return (None,
1343 "\n",
1344 "\r",
1345 ("\r", "\n"),
1346 "\r\n",
1347 ("\n", "\r\n"),
1348 ("\r", "\r\n"),
1349 ("\r", "\n", "\r\n")
1350 )[self.seennl]
1351
1352
Guido van Rossum78892e42007-04-06 17:31:18 +00001353class TextIOWrapper(TextIOBase):
1354
Christian Heimes5d8da202008-05-06 13:58:24 +00001355 r"""Character and line based layer over a BufferedIOBase object, buffer.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001356
1357 encoding gives the name of the encoding that the stream will be
1358 decoded or encoded with. It defaults to locale.getpreferredencoding.
1359
1360 errors determines the strictness of encoding and decoding (see the
1361 codecs.register) and defaults to "strict".
1362
1363 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1364 handling of line endings. If it is None, universal newlines is
1365 enabled. With this enabled, on input, the lines endings '\n', '\r',
1366 or '\r\n' are translated to '\n' before being returned to the
1367 caller. Conversely, on output, '\n' is translated to the system
1368 default line seperator, os.linesep. If newline is any other of its
1369 legal values, that newline becomes the newline when the file is read
1370 and it is returned untranslated. On output, '\n' is converted to the
1371 newline.
1372
1373 If line_buffering is True, a call to flush is implied when a call to
1374 write contains a newline character.
Guido van Rossum78892e42007-04-06 17:31:18 +00001375 """
1376
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001377 _CHUNK_SIZE = 128
Guido van Rossum78892e42007-04-06 17:31:18 +00001378
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001379 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1380 line_buffering=False):
Guido van Rossum8358db22007-08-18 21:39:55 +00001381 if newline not in (None, "", "\n", "\r", "\r\n"):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001382 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +00001383 if encoding is None:
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001384 try:
1385 encoding = os.device_encoding(buffer.fileno())
Brett Cannon041683d2007-10-11 23:08:53 +00001386 except (AttributeError, UnsupportedOperation):
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001387 pass
1388 if encoding is None:
Martin v. Löwisd78d3b42007-08-11 15:36:45 +00001389 try:
1390 import locale
1391 except ImportError:
1392 # Importing locale may fail if Python is being built
1393 encoding = "ascii"
1394 else:
1395 encoding = locale.getpreferredencoding()
Guido van Rossum78892e42007-04-06 17:31:18 +00001396
Christian Heimes8bd14fb2007-11-08 16:34:32 +00001397 if not isinstance(encoding, str):
1398 raise ValueError("invalid encoding: %r" % encoding)
1399
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001400 if errors is None:
1401 errors = "strict"
1402 else:
1403 if not isinstance(errors, str):
1404 raise ValueError("invalid errors: %r" % errors)
1405
Guido van Rossum78892e42007-04-06 17:31:18 +00001406 self.buffer = buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001407 self._line_buffering = line_buffering
Guido van Rossum78892e42007-04-06 17:31:18 +00001408 self._encoding = encoding
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001409 self._errors = errors
Guido van Rossum8358db22007-08-18 21:39:55 +00001410 self._readuniversal = not newline
1411 self._readtranslate = newline is None
1412 self._readnl = newline
1413 self._writetranslate = newline != ''
1414 self._writenl = newline or os.linesep
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001415 self._encoder = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001416 self._decoder = None
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001417 self._decoded_chars = '' # buffer for text returned from decoder
1418 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001419 self._snapshot = None # info for reconstructing decoder state
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001420 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001421
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001422 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1423 # where dec_flags is the second (integer) item of the decoder state
1424 # and next_input is the chunk of input bytes that comes next after the
1425 # snapshot point. We use this to reconstruct decoder states in tell().
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001426
1427 # Naming convention:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001428 # - "bytes_..." for integer variables that count input bytes
1429 # - "chars_..." for integer variables that count decoded characters
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001430
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001431 @property
1432 def encoding(self):
1433 return self._encoding
1434
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001435 @property
1436 def errors(self):
1437 return self._errors
1438
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001439 @property
1440 def line_buffering(self):
1441 return self._line_buffering
1442
Ka-Ping Yeeddaa7062008-03-17 20:35:15 +00001443 def seekable(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001444 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +00001445
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001446 def readable(self):
1447 return self.buffer.readable()
1448
1449 def writable(self):
1450 return self.buffer.writable()
1451
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001452 def flush(self):
1453 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001454 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001455
1456 def close(self):
Guido van Rossum33e7a8e2007-07-22 20:38:07 +00001457 try:
1458 self.flush()
1459 except:
1460 pass # If flush() fails, just give up
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001461 self.buffer.close()
1462
1463 @property
1464 def closed(self):
1465 return self.buffer.closed
1466
Guido van Rossum9be55972007-04-07 02:59:27 +00001467 def fileno(self):
1468 return self.buffer.fileno()
1469
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001470 def isatty(self):
1471 return self.buffer.isatty()
1472
Guido van Rossum78892e42007-04-06 17:31:18 +00001473 def write(self, s: str):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001474 if self.closed:
1475 raise ValueError("write to closed file")
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001476 if not isinstance(s, str):
Guido van Rossumdcce8392007-08-29 18:10:08 +00001477 raise TypeError("can't write %s to text stream" %
1478 s.__class__.__name__)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001479 length = len(s)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001480 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
Guido van Rossum8358db22007-08-18 21:39:55 +00001481 if haslf and self._writetranslate and self._writenl != "\n":
1482 s = s.replace("\n", self._writenl)
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001483 encoder = self._encoder or self._get_encoder()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001484 # XXX What if we were just reading?
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001485 b = encoder.encode(s)
Guido van Rossum8358db22007-08-18 21:39:55 +00001486 self.buffer.write(b)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001487 if self._line_buffering and (haslf or "\r" in s):
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001488 self.flush()
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001489 self._snapshot = None
1490 if self._decoder:
1491 self._decoder.reset()
1492 return length
Guido van Rossum78892e42007-04-06 17:31:18 +00001493
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001494 def _get_encoder(self):
1495 make_encoder = codecs.getincrementalencoder(self._encoding)
1496 self._encoder = make_encoder(self._errors)
1497 return self._encoder
1498
Guido van Rossum78892e42007-04-06 17:31:18 +00001499 def _get_decoder(self):
1500 make_decoder = codecs.getincrementaldecoder(self._encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001501 decoder = make_decoder(self._errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001502 if self._readuniversal:
1503 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1504 self._decoder = decoder
Guido van Rossum78892e42007-04-06 17:31:18 +00001505 return decoder
1506
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001507 # The following three methods implement an ADT for _decoded_chars.
1508 # Text returned from the decoder is buffered here until the client
1509 # requests it by calling our read() or readline() method.
1510 def _set_decoded_chars(self, chars):
1511 """Set the _decoded_chars buffer."""
1512 self._decoded_chars = chars
1513 self._decoded_chars_used = 0
1514
1515 def _get_decoded_chars(self, n=None):
1516 """Advance into the _decoded_chars buffer."""
1517 offset = self._decoded_chars_used
1518 if n is None:
1519 chars = self._decoded_chars[offset:]
1520 else:
1521 chars = self._decoded_chars[offset:offset + n]
1522 self._decoded_chars_used += len(chars)
1523 return chars
1524
1525 def _rewind_decoded_chars(self, n):
1526 """Rewind the _decoded_chars buffer."""
1527 if self._decoded_chars_used < n:
1528 raise AssertionError("rewind decoded_chars out of bounds")
1529 self._decoded_chars_used -= n
1530
Guido van Rossum9b76da62007-04-11 01:09:03 +00001531 def _read_chunk(self):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001532 """
1533 Read and decode the next chunk of data from the BufferedReader.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001534 """
1535
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001536 # The return value is True unless EOF was reached. The decoded
1537 # string is placed in self._decoded_chars (replacing its previous
1538 # value). The entire input chunk is sent to the decoder, though
1539 # some of it may remain buffered in the decoder, yet to be
1540 # converted.
1541
Guido van Rossum5abbf752007-08-27 17:39:33 +00001542 if self._decoder is None:
1543 raise ValueError("no decoder")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001544
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001545 if self._telling:
1546 # To prepare for tell(), we need to snapshot a point in the
1547 # file where the decoder's input buffer is empty.
Guido van Rossum9b76da62007-04-11 01:09:03 +00001548
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001549 dec_buffer, dec_flags = self._decoder.getstate()
1550 # Given this, we know there was a valid snapshot point
1551 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001552
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001553 # Read a chunk, decode it, and put the result in self._decoded_chars.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001554 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1555 eof = not input_chunk
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001556 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001557
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001558 if self._telling:
1559 # At the snapshot point, len(dec_buffer) bytes before the read,
1560 # the next input to be decoded is dec_buffer + input_chunk.
1561 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1562
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001563 return not eof
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001564
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001565 def _pack_cookie(self, position, dec_flags=0,
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001566 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001567 # The meaning of a tell() cookie is: seek to position, set the
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001568 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001569 # into the decoder with need_eof as the EOF flag, then skip
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001570 # chars_to_skip characters of the decoded result. For most simple
1571 # decoders, tell() will often just give a byte offset in the file.
1572 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1573 (chars_to_skip<<192) | bool(need_eof)<<256)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001574
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001575 def _unpack_cookie(self, bigint):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001576 rest, position = divmod(bigint, 1<<64)
1577 rest, dec_flags = divmod(rest, 1<<64)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001578 rest, bytes_to_feed = divmod(rest, 1<<64)
1579 need_eof, chars_to_skip = divmod(rest, 1<<64)
1580 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
Guido van Rossum9b76da62007-04-11 01:09:03 +00001581
1582 def tell(self):
1583 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001584 raise IOError("underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001585 if not self._telling:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001586 raise IOError("telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001587 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001588 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001589 decoder = self._decoder
1590 if decoder is None or self._snapshot is None:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001591 if self._decoded_chars:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001592 # This should never happen.
1593 raise AssertionError("pending decoded text")
Guido van Rossumcba608c2007-04-11 14:19:59 +00001594 return position
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001595
1596 # Skip backward to the snapshot point (see _read_chunk).
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001597 dec_flags, next_input = self._snapshot
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001598 position -= len(next_input)
1599
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001600 # How many decoded characters have been used up since the snapshot?
1601 chars_to_skip = self._decoded_chars_used
1602 if chars_to_skip == 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001603 # We haven't moved from the snapshot point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001604 return self._pack_cookie(position, dec_flags)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001605
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001606 # Starting from the snapshot position, we will walk the decoder
1607 # forward until it gives us enough decoded characters.
Guido van Rossumd76e7792007-04-17 02:38:04 +00001608 saved_state = decoder.getstate()
1609 try:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001610 # Note our initial start point.
1611 decoder.setstate((b'', dec_flags))
1612 start_pos = position
1613 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001614 need_eof = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001615
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001616 # Feed the decoder one byte at a time. As we go, note the
1617 # nearest "safe start point" before the current location
1618 # (a point where the decoder has nothing buffered, so seek()
1619 # can safely start from there and advance to this location).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001620 next_byte = bytearray(1)
1621 for next_byte[0] in next_input:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001622 bytes_fed += 1
1623 chars_decoded += len(decoder.decode(next_byte))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001624 dec_buffer, dec_flags = decoder.getstate()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001625 if not dec_buffer and chars_decoded <= chars_to_skip:
1626 # Decoder buffer is empty, so this is a safe start point.
1627 start_pos += bytes_fed
1628 chars_to_skip -= chars_decoded
1629 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1630 if chars_decoded >= chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001631 break
1632 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001633 # We didn't get enough decoded data; signal EOF to get more.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001634 chars_decoded += len(decoder.decode(b'', final=True))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001635 need_eof = 1
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001636 if chars_decoded < chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001637 raise IOError("can't reconstruct logical file position")
1638
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001639 # The returned cookie corresponds to the last safe start point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001640 return self._pack_cookie(
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001641 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001642 finally:
1643 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001644
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001645 def truncate(self, pos=None):
1646 self.flush()
1647 if pos is None:
1648 pos = self.tell()
1649 self.seek(pos)
1650 return self.buffer.truncate()
1651
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001652 def seek(self, cookie, whence=0):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001653 if self.closed:
1654 raise ValueError("tell on closed file")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001655 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001656 raise IOError("underlying stream is not seekable")
1657 if whence == 1: # seek relative to current position
1658 if cookie != 0:
1659 raise IOError("can't do nonzero cur-relative seeks")
1660 # Seeking to the current position should attempt to
1661 # sync the underlying buffer with the current position.
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001662 whence = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001663 cookie = self.tell()
1664 if whence == 2: # seek relative to end of file
1665 if cookie != 0:
1666 raise IOError("can't do nonzero end-relative seeks")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001667 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001668 position = self.buffer.seek(0, 2)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001669 self._set_decoded_chars('')
1670 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001671 if self._decoder:
1672 self._decoder.reset()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001673 return position
Guido van Rossum9b76da62007-04-11 01:09:03 +00001674 if whence != 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001675 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
Guido van Rossum9b76da62007-04-11 01:09:03 +00001676 (whence,))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001677 if cookie < 0:
1678 raise ValueError("negative seek position %r" % (cookie,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001679 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001680
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001681 # The strategy of seek() is to go back to the safe start point
1682 # and replay the effect of read(chars_to_skip) from there.
1683 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001684 self._unpack_cookie(cookie)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001685
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001686 # Seek back to the safe start point.
1687 self.buffer.seek(start_pos)
1688 self._set_decoded_chars('')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001689 self._snapshot = None
1690
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001691 # Restore the decoder to its state from the safe start point.
1692 if self._decoder or dec_flags or chars_to_skip:
1693 self._decoder = self._decoder or self._get_decoder()
1694 self._decoder.setstate((b'', dec_flags))
1695 self._snapshot = (dec_flags, b'')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001696
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001697 if chars_to_skip:
1698 # Just like _read_chunk, feed the decoder and save a snapshot.
1699 input_chunk = self.buffer.read(bytes_to_feed)
1700 self._set_decoded_chars(
1701 self._decoder.decode(input_chunk, need_eof))
1702 self._snapshot = (dec_flags, input_chunk)
1703
1704 # Skip chars_to_skip of the decoded characters.
1705 if len(self._decoded_chars) < chars_to_skip:
1706 raise IOError("can't restore logical file position")
1707 self._decoded_chars_used = chars_to_skip
1708
1709 return cookie
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001710
Guido van Rossum024da5c2007-05-17 23:59:11 +00001711 def read(self, n=None):
1712 if n is None:
1713 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001714 decoder = self._decoder or self._get_decoder()
Guido van Rossum78892e42007-04-06 17:31:18 +00001715 if n < 0:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001716 # Read everything.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001717 result = (self._get_decoded_chars() +
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001718 decoder.decode(self.buffer.read(), final=True))
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001719 self._set_decoded_chars('')
1720 self._snapshot = None
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001721 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001722 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001723 # Keep reading chunks until we have n characters to return.
1724 eof = False
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001725 result = self._get_decoded_chars(n)
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001726 while len(result) < n and not eof:
1727 eof = not self._read_chunk()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001728 result += self._get_decoded_chars(n - len(result))
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001729 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001730
Guido van Rossum024da5c2007-05-17 23:59:11 +00001731 def __next__(self):
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001732 self._telling = False
1733 line = self.readline()
1734 if not line:
1735 self._snapshot = None
1736 self._telling = self._seekable
1737 raise StopIteration
1738 return line
1739
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001740 def readline(self, limit=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001741 if self.closed:
1742 raise ValueError("read from closed file")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001743 if limit is None:
1744 limit = -1
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001745
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001746 # Grab all the decoded text (we will rewind any extra bits later).
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001747 line = self._get_decoded_chars()
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001748
Guido van Rossum78892e42007-04-06 17:31:18 +00001749 start = 0
1750 decoder = self._decoder or self._get_decoder()
1751
Guido van Rossum8358db22007-08-18 21:39:55 +00001752 pos = endpos = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001753 while True:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001754 if self._readtranslate:
1755 # Newlines are already translated, only search for \n
1756 pos = line.find('\n', start)
1757 if pos >= 0:
1758 endpos = pos + 1
1759 break
1760 else:
1761 start = len(line)
1762
1763 elif self._readuniversal:
Guido van Rossum8358db22007-08-18 21:39:55 +00001764 # Universal newline search. Find any of \r, \r\n, \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001765 # The decoder ensures that \r\n are not split in two pieces
Guido van Rossum78892e42007-04-06 17:31:18 +00001766
Guido van Rossum8358db22007-08-18 21:39:55 +00001767 # In C we'd look for these in parallel of course.
1768 nlpos = line.find("\n", start)
1769 crpos = line.find("\r", start)
1770 if crpos == -1:
1771 if nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001772 # Nothing found
Guido van Rossum8358db22007-08-18 21:39:55 +00001773 start = len(line)
Guido van Rossum78892e42007-04-06 17:31:18 +00001774 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001775 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001776 endpos = nlpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001777 break
1778 elif nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001779 # Found lone \r
1780 endpos = crpos + 1
1781 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001782 elif nlpos < crpos:
1783 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001784 endpos = nlpos + 1
Guido van Rossum78892e42007-04-06 17:31:18 +00001785 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001786 elif nlpos == crpos + 1:
1787 # Found \r\n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001788 endpos = crpos + 2
Guido van Rossum8358db22007-08-18 21:39:55 +00001789 break
1790 else:
1791 # Found \r
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001792 endpos = crpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001793 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001794 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001795 # non-universal
1796 pos = line.find(self._readnl)
1797 if pos >= 0:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001798 endpos = pos + len(self._readnl)
Guido van Rossum8358db22007-08-18 21:39:55 +00001799 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001800
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001801 if limit >= 0 and len(line) >= limit:
1802 endpos = limit # reached length limit
1803 break
1804
Guido van Rossum78892e42007-04-06 17:31:18 +00001805 # No line ending seen yet - get more data
Guido van Rossum8358db22007-08-18 21:39:55 +00001806 more_line = ''
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001807 while self._read_chunk():
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001808 if self._decoded_chars:
Guido van Rossum78892e42007-04-06 17:31:18 +00001809 break
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001810 if self._decoded_chars:
1811 line += self._get_decoded_chars()
Guido van Rossum8358db22007-08-18 21:39:55 +00001812 else:
1813 # end of file
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001814 self._set_decoded_chars('')
1815 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001816 return line
Guido van Rossum78892e42007-04-06 17:31:18 +00001817
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001818 if limit >= 0 and endpos > limit:
1819 endpos = limit # don't exceed limit
1820
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001821 # Rewind _decoded_chars to just after the line ending we found.
1822 self._rewind_decoded_chars(len(line) - endpos)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001823 return line[:endpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001824
Guido van Rossum8358db22007-08-18 21:39:55 +00001825 @property
1826 def newlines(self):
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001827 return self._decoder.newlines if self._decoder else None
Guido van Rossum024da5c2007-05-17 23:59:11 +00001828
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001829class _StringIO(TextIOWrapper):
1830 """Text I/O implementation using an in-memory buffer.
1831
1832 The initial_value argument sets the value of object. The newline
1833 argument is like the one of TextIOWrapper's constructor.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001834 """
Guido van Rossum024da5c2007-05-17 23:59:11 +00001835
1836 # XXX This is really slow, but fully functional
1837
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001838 def __init__(self, initial_value="", newline="\n"):
1839 super(_StringIO, self).__init__(BytesIO(),
1840 encoding="utf-8",
1841 errors="strict",
1842 newline=newline)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001843 if initial_value:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001844 if not isinstance(initial_value, str):
Guido van Rossum34d19282007-08-09 01:03:29 +00001845 initial_value = str(initial_value)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001846 self.write(initial_value)
1847 self.seek(0)
1848
1849 def getvalue(self):
Guido van Rossum34d19282007-08-09 01:03:29 +00001850 self.flush()
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001851 return self.buffer.getvalue().decode(self._encoding, self._errors)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001852
1853try:
1854 import _stringio
1855
1856 # This subclass is a reimplementation of the TextIOWrapper
1857 # interface without any of its text decoding facilities. All the
1858 # stored data is manipulated with the efficient
1859 # _stringio._StringIO extension type. Also, the newline decoding
1860 # mechanism of IncrementalNewlineDecoder is reimplemented here for
1861 # efficiency. Doing otherwise, would require us to implement a
1862 # fake decoder which would add an additional and unnecessary layer
1863 # on top of the _StringIO methods.
1864
1865 class StringIO(_stringio._StringIO, TextIOBase):
1866 """Text I/O implementation using an in-memory buffer.
1867
1868 The initial_value argument sets the value of object. The newline
1869 argument is like the one of TextIOWrapper's constructor.
1870 """
1871
1872 _CHUNK_SIZE = 4096
1873
1874 def __init__(self, initial_value="", newline="\n"):
1875 if newline not in (None, "", "\n", "\r", "\r\n"):
1876 raise ValueError("illegal newline value: %r" % (newline,))
1877
1878 self._readuniversal = not newline
1879 self._readtranslate = newline is None
1880 self._readnl = newline
1881 self._writetranslate = newline != ""
1882 self._writenl = newline or os.linesep
1883 self._pending = ""
1884 self._seennl = 0
1885
1886 # Reset the buffer first, in case __init__ is called
1887 # multiple times.
1888 self.truncate(0)
1889 if initial_value is None:
1890 initial_value = ""
1891 self.write(initial_value)
1892 self.seek(0)
1893
1894 @property
1895 def buffer(self):
1896 raise UnsupportedOperation("%s.buffer attribute is unsupported" %
1897 self.__class__.__name__)
1898
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +00001899 # XXX Cruft to support the TextIOWrapper API. This would only
1900 # be meaningful if StringIO supported the buffer attribute.
1901 # Hopefully, a better solution, than adding these pseudo-attributes,
1902 # will be found.
1903 @property
1904 def encoding(self):
1905 return "utf-8"
1906
1907 @property
1908 def errors(self):
1909 return "strict"
1910
1911 @property
1912 def line_buffering(self):
1913 return False
1914
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001915 def _decode_newlines(self, input, final=False):
1916 # decode input (with the eventual \r from a previous pass)
1917 if self._pending:
1918 input = self._pending + input
1919
1920 # retain last \r even when not translating data:
1921 # then readline() is sure to get \r\n in one pass
1922 if input.endswith("\r") and not final:
1923 input = input[:-1]
1924 self._pending = "\r"
1925 else:
1926 self._pending = ""
1927
1928 # Record which newlines are read
1929 crlf = input.count('\r\n')
1930 cr = input.count('\r') - crlf
1931 lf = input.count('\n') - crlf
1932 self._seennl |= (lf and self._LF) | (cr and self._CR) \
1933 | (crlf and self._CRLF)
1934
1935 if self._readtranslate:
1936 if crlf:
1937 output = input.replace("\r\n", "\n")
1938 if cr:
1939 output = input.replace("\r", "\n")
1940 else:
1941 output = input
1942
1943 return output
1944
1945 def writable(self):
1946 return True
1947
1948 def readable(self):
1949 return True
1950
1951 def seekable(self):
1952 return True
1953
1954 _read = _stringio._StringIO.read
1955 _write = _stringio._StringIO.write
1956 _tell = _stringio._StringIO.tell
1957 _seek = _stringio._StringIO.seek
1958 _truncate = _stringio._StringIO.truncate
1959 _getvalue = _stringio._StringIO.getvalue
1960
1961 def getvalue(self) -> str:
1962 """Retrieve the entire contents of the object."""
1963 if self.closed:
1964 raise ValueError("read on closed file")
1965 return self._getvalue()
1966
1967 def write(self, s: str) -> int:
1968 """Write string s to file.
1969
1970 Returns the number of characters written.
1971 """
1972 if self.closed:
1973 raise ValueError("write to closed file")
1974 if not isinstance(s, str):
1975 raise TypeError("can't write %s to text stream" %
1976 s.__class__.__name__)
1977 length = len(s)
1978 if self._writetranslate and self._writenl != "\n":
1979 s = s.replace("\n", self._writenl)
1980 self._pending = ""
1981 self._write(s)
1982 return length
1983
1984 def read(self, n: int = None) -> str:
1985 """Read at most n characters, returned as a string.
1986
1987 If the argument is negative or omitted, read until EOF
1988 is reached. Return an empty string at EOF.
1989 """
1990 if self.closed:
1991 raise ValueError("read to closed file")
1992 if n is None:
1993 n = -1
1994 res = self._pending
1995 if n < 0:
1996 res += self._decode_newlines(self._read(), True)
1997 self._pending = ""
1998 return res
1999 else:
2000 res = self._decode_newlines(self._read(n), True)
2001 self._pending = res[n:]
2002 return res[:n]
2003
2004 def tell(self) -> int:
2005 """Tell the current file position."""
2006 if self.closed:
2007 raise ValueError("tell from closed file")
2008 if self._pending:
2009 return self._tell() - len(self._pending)
2010 else:
2011 return self._tell()
2012
2013 def seek(self, pos: int = None, whence: int = 0) -> int:
2014 """Change stream position.
2015
2016 Seek to character offset pos relative to position indicated by whence:
2017 0 Start of stream (the default). pos should be >= 0;
2018 1 Current position - pos must be 0;
2019 2 End of stream - pos must be 0.
2020 Returns the new absolute position.
2021 """
2022 if self.closed:
2023 raise ValueError("seek from closed file")
2024 self._pending = ""
2025 return self._seek(pos, whence)
2026
2027 def truncate(self, pos: int = None) -> int:
2028 """Truncate size to pos.
2029
2030 The pos argument defaults to the current file position, as
2031 returned by tell(). Imply an absolute seek to pos.
2032 Returns the new absolute position.
2033 """
2034 if self.closed:
2035 raise ValueError("truncate from closed file")
2036 self._pending = ""
2037 return self._truncate(pos)
2038
2039 def readline(self, limit: int = None) -> str:
2040 if self.closed:
2041 raise ValueError("read from closed file")
2042 if limit is None:
2043 limit = -1
2044 if limit >= 0:
2045 # XXX: Hack to support limit argument, for backwards
2046 # XXX compatibility
2047 line = self.readline()
2048 if len(line) <= limit:
2049 return line
2050 line, self._pending = line[:limit], line[limit:] + self._pending
2051 return line
2052
2053 line = self._pending
2054 self._pending = ""
2055
2056 start = 0
2057 pos = endpos = None
2058 while True:
2059 if self._readtranslate:
2060 # Newlines are already translated, only search for \n
2061 pos = line.find('\n', start)
2062 if pos >= 0:
2063 endpos = pos + 1
2064 break
2065 else:
2066 start = len(line)
2067
2068 elif self._readuniversal:
2069 # Universal newline search. Find any of \r, \r\n, \n
2070 # The decoder ensures that \r\n are not split in two pieces
2071
2072 # In C we'd look for these in parallel of course.
2073 nlpos = line.find("\n", start)
2074 crpos = line.find("\r", start)
2075 if crpos == -1:
2076 if nlpos == -1:
2077 # Nothing found
2078 start = len(line)
2079 else:
2080 # Found \n
2081 endpos = nlpos + 1
2082 break
2083 elif nlpos == -1:
2084 # Found lone \r
2085 endpos = crpos + 1
2086 break
2087 elif nlpos < crpos:
2088 # Found \n
2089 endpos = nlpos + 1
2090 break
2091 elif nlpos == crpos + 1:
2092 # Found \r\n
2093 endpos = crpos + 2
2094 break
2095 else:
2096 # Found \r
2097 endpos = crpos + 1
2098 break
2099 else:
2100 # non-universal
2101 pos = line.find(self._readnl)
2102 if pos >= 0:
2103 endpos = pos + len(self._readnl)
2104 break
2105
2106 # No line ending seen yet - get more data
2107 more_line = self.read(self._CHUNK_SIZE)
2108 if more_line:
2109 line += more_line
2110 else:
2111 # end of file
2112 return line
2113
2114 self._pending = line[endpos:]
2115 return line[:endpos]
2116
2117 _LF = 1
2118 _CR = 2
2119 _CRLF = 4
2120
2121 @property
2122 def newlines(self):
2123 return (None,
2124 "\n",
2125 "\r",
2126 ("\r", "\n"),
2127 "\r\n",
2128 ("\n", "\r\n"),
2129 ("\r", "\r\n"),
2130 ("\r", "\n", "\r\n")
2131 )[self._seennl]
2132
2133
2134except ImportError:
2135 StringIO = _StringIO