blob: d41da60b9162c4c46ed9743e2cbb260f7ec1ae36 [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
Mark Dickinson934896d2009-02-21 20:59:32 +00006separation between reading and writing to streams; implementations are
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00007allowed 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:
242 return raw
243 raise ValueError("can't have unbuffered text I/O")
244 if updating:
245 buffer = BufferedRandom(raw, buffering)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000246 elif writing or appending:
Guido van Rossum28524c72007-02-27 05:47:44 +0000247 buffer = BufferedWriter(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000248 elif reading:
Guido van Rossum28524c72007-02-27 05:47:44 +0000249 buffer = BufferedReader(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000250 else:
251 raise ValueError("unknown mode: %r" % mode)
Guido van Rossum28524c72007-02-27 05:47:44 +0000252 if binary:
253 return buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000254 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000255 text.mode = mode
256 return text
Guido van Rossum28524c72007-02-27 05:47:44 +0000257
Christian Heimesa33eb062007-12-08 17:47:40 +0000258class _DocDescriptor:
259 """Helper for builtins.open.__doc__
260 """
261 def __get__(self, obj, typ):
262 return (
263 "open(file, mode='r', buffering=None, encoding=None, "
264 "errors=None, newline=None, closefd=True)\n\n" +
265 open.__doc__)
Guido van Rossum28524c72007-02-27 05:47:44 +0000266
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000267class OpenWrapper:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000268 """Wrapper for builtins.open
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000269
270 Trick so that open won't become a bound method when stored
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000271 as a class variable (as dbm.dumb does).
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000272
273 See initstdio() in Python/pythonrun.c.
274 """
Christian Heimesa33eb062007-12-08 17:47:40 +0000275 __doc__ = _DocDescriptor()
276
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000277 def __new__(cls, *args, **kwargs):
278 return open(*args, **kwargs)
279
280
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000281class UnsupportedOperation(ValueError, IOError):
282 pass
283
284
Guido van Rossumb7f136e2007-08-22 18:14:10 +0000285class IOBase(metaclass=abc.ABCMeta):
Guido van Rossum28524c72007-02-27 05:47:44 +0000286
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000287 """The abstract base class for all I/O classes, acting on streams of
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000288 bytes. There is no public constructor.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000289
Guido van Rossum141f7672007-04-10 00:22:16 +0000290 This class provides dummy implementations for many methods that
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000291 derived classes can override selectively; the default implementations
292 represent a file that cannot be read, written or seeked.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000293
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000294 Even though IOBase does not declare read, readinto, or write because
295 their signatures will vary, implementations and clients should
296 consider those methods part of the interface. Also, implementations
297 may raise a IOError when operations they do not support are called.
Guido van Rossum53807da2007-04-10 19:01:47 +0000298
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000299 The basic type used for binary data read from or written to a file is
300 bytes. bytearrays are accepted too, and in some cases (such as
301 readinto) needed. Text I/O classes work with str data.
302
303 Note that calling any method (even inquiries) on a closed stream is
Benjamin Peterson9a89e962008-04-06 16:47:13 +0000304 undefined. Implementations may raise IOError in this case.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000305
306 IOBase (and its subclasses) support the iterator protocol, meaning
307 that an IOBase object can be iterated over yielding the lines in a
308 stream.
309
310 IOBase also supports the :keyword:`with` statement. In this example,
311 fp is closed after the suite of the with statment is complete:
312
313 with open('spam.txt', 'r') as fp:
314 fp.write('Spam and eggs!')
Guido van Rossum17e43e52007-02-27 15:45:13 +0000315 """
316
Guido van Rossum141f7672007-04-10 00:22:16 +0000317 ### Internal ###
318
319 def _unsupported(self, name: str) -> IOError:
320 """Internal: raise an exception for unsupported operations."""
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000321 raise UnsupportedOperation("%s.%s() not supported" %
322 (self.__class__.__name__, name))
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000323
Guido van Rossum141f7672007-04-10 00:22:16 +0000324 ### Positioning ###
325
Guido van Rossum53807da2007-04-10 19:01:47 +0000326 def seek(self, pos: int, whence: int = 0) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000327 """Change stream position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000328
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000329 Change the stream position to byte offset offset. offset is
330 interpreted relative to the position indicated by whence. Values
331 for whence are:
332
333 * 0 -- start of stream (the default); offset should be zero or positive
334 * 1 -- current stream position; offset may be negative
335 * 2 -- end of stream; offset is usually negative
336
337 Return the new absolute position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000338 """
339 self._unsupported("seek")
340
341 def tell(self) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000342 """Return current stream position."""
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000343 self._checkClosed()
Guido van Rossum53807da2007-04-10 19:01:47 +0000344 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000345
Guido van Rossum87429772007-04-10 21:06:59 +0000346 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000347 """Truncate file to size bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000348
Christian Heimes5d8da202008-05-06 13:58:24 +0000349 Size defaults to the current IO position as reported by tell(). Return
350 the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000351 """
352 self._unsupported("truncate")
353
354 ### Flush and close ###
355
356 def flush(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000357 """Flush write buffers, if applicable.
Guido van Rossum141f7672007-04-10 00:22:16 +0000358
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000359 This is not implemented for read-only and non-blocking streams.
Guido van Rossum141f7672007-04-10 00:22:16 +0000360 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000361 # XXX Should this return the number of bytes written???
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000362 if self.__closed:
363 raise ValueError("I/O operation on closed file.")
Guido van Rossum141f7672007-04-10 00:22:16 +0000364
365 __closed = False
366
367 def close(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000368 """Flush and close the IO object.
Guido van Rossum141f7672007-04-10 00:22:16 +0000369
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000370 This method has no effect if the file is already closed.
Guido van Rossum141f7672007-04-10 00:22:16 +0000371 """
372 if not self.__closed:
Guido van Rossum469734b2007-07-10 12:00:45 +0000373 try:
374 self.flush()
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000375 except IOError:
376 pass # If flush() fails, just give up
377 self.__closed = True
Guido van Rossum141f7672007-04-10 00:22:16 +0000378
379 def __del__(self) -> None:
380 """Destructor. Calls close()."""
381 # The try/except block is in case this is called at program
382 # exit time, when it's possible that globals have already been
383 # deleted, and then the close() call might fail. Since
384 # there's nothing we can do about such failures and they annoy
385 # the end users, we suppress the traceback.
386 try:
387 self.close()
388 except:
389 pass
390
391 ### Inquiries ###
392
393 def seekable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000394 """Return whether object supports random access.
Guido van Rossum141f7672007-04-10 00:22:16 +0000395
396 If False, seek(), tell() and truncate() will raise IOError.
397 This method may need to do a test seek().
398 """
399 return False
400
Guido van Rossum5abbf752007-08-27 17:39:33 +0000401 def _checkSeekable(self, msg=None):
402 """Internal: raise an IOError if file is not seekable
403 """
404 if not self.seekable():
405 raise IOError("File or stream is not seekable."
406 if msg is None else msg)
407
408
Guido van Rossum141f7672007-04-10 00:22:16 +0000409 def readable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000410 """Return whether object was opened for reading.
Guido van Rossum141f7672007-04-10 00:22:16 +0000411
412 If False, read() will raise IOError.
413 """
414 return False
415
Guido van Rossum5abbf752007-08-27 17:39:33 +0000416 def _checkReadable(self, msg=None):
417 """Internal: raise an IOError if file is not readable
418 """
419 if not self.readable():
420 raise IOError("File or stream is not readable."
421 if msg is None else msg)
422
Guido van Rossum141f7672007-04-10 00:22:16 +0000423 def writable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000424 """Return whether object was opened for writing.
Guido van Rossum141f7672007-04-10 00:22:16 +0000425
426 If False, write() and truncate() will raise IOError.
427 """
428 return False
429
Guido van Rossum5abbf752007-08-27 17:39:33 +0000430 def _checkWritable(self, msg=None):
431 """Internal: raise an IOError if file is not writable
432 """
433 if not self.writable():
434 raise IOError("File or stream is not writable."
435 if msg is None else msg)
436
Guido van Rossum141f7672007-04-10 00:22:16 +0000437 @property
438 def closed(self):
439 """closed: bool. True iff the file has been closed.
440
441 For backwards compatibility, this is a property, not a predicate.
442 """
443 return self.__closed
444
Guido van Rossum5abbf752007-08-27 17:39:33 +0000445 def _checkClosed(self, msg=None):
446 """Internal: raise an ValueError if file is closed
447 """
448 if self.closed:
449 raise ValueError("I/O operation on closed file."
450 if msg is None else msg)
451
Guido van Rossum141f7672007-04-10 00:22:16 +0000452 ### Context manager ###
453
454 def __enter__(self) -> "IOBase": # That's a forward reference
455 """Context management protocol. Returns self."""
Christian Heimes3ecfea712008-02-09 20:51:34 +0000456 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000457 return self
458
459 def __exit__(self, *args) -> None:
460 """Context management protocol. Calls close()"""
461 self.close()
462
463 ### Lower-level APIs ###
464
465 # XXX Should these be present even if unimplemented?
466
467 def fileno(self) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000468 """Returns underlying file descriptor if one exists.
Guido van Rossum141f7672007-04-10 00:22:16 +0000469
Christian Heimes5d8da202008-05-06 13:58:24 +0000470 An IOError is raised if the IO object does not use a file descriptor.
Guido van Rossum141f7672007-04-10 00:22:16 +0000471 """
472 self._unsupported("fileno")
473
474 def isatty(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000475 """Return whether this is an 'interactive' stream.
476
477 Return False if it can't be determined.
Guido van Rossum141f7672007-04-10 00:22:16 +0000478 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000479 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000480 return False
481
Guido van Rossum7165cb12007-07-10 06:54:34 +0000482 ### Readline[s] and writelines ###
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000483
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000484 def readline(self, limit: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000485 r"""Read and return a line from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000486
487 If limit is specified, at most limit bytes will be read.
488
489 The line terminator is always b'\n' for binary files; for text
490 files, the newlines argument to open can be used to select the line
491 terminator(s) recognized.
492 """
493 # For backwards compatibility, a (slowish) readline().
Guido van Rossum2bf71382007-06-08 00:07:57 +0000494 if hasattr(self, "peek"):
495 def nreadahead():
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000496 readahead = self.peek(1)
Guido van Rossum2bf71382007-06-08 00:07:57 +0000497 if not readahead:
498 return 1
499 n = (readahead.find(b"\n") + 1) or len(readahead)
500 if limit >= 0:
501 n = min(n, limit)
502 return n
503 else:
504 def nreadahead():
505 return 1
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000506 if limit is None:
507 limit = -1
Guido van Rossum254348e2007-11-21 19:29:53 +0000508 res = bytearray()
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000509 while limit < 0 or len(res) < limit:
Guido van Rossum2bf71382007-06-08 00:07:57 +0000510 b = self.read(nreadahead())
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000511 if not b:
512 break
513 res += b
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000514 if res.endswith(b"\n"):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000515 break
Guido van Rossum98297ee2007-11-06 21:34:58 +0000516 return bytes(res)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000517
Guido van Rossum7165cb12007-07-10 06:54:34 +0000518 def __iter__(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000519 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000520 return self
521
522 def __next__(self):
523 line = self.readline()
524 if not line:
525 raise StopIteration
526 return line
527
528 def readlines(self, hint=None):
Christian Heimes5d8da202008-05-06 13:58:24 +0000529 """Return a list of lines from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000530
531 hint can be specified to control the number of lines read: no more
532 lines will be read if the total size (in bytes/characters) of all
533 lines so far exceeds hint.
534 """
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000535 if hint is None or hint <= 0:
Guido van Rossum7165cb12007-07-10 06:54:34 +0000536 return list(self)
537 n = 0
538 lines = []
539 for line in self:
540 lines.append(line)
541 n += len(line)
542 if n >= hint:
543 break
544 return lines
545
546 def writelines(self, lines):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000547 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000548 for line in lines:
549 self.write(line)
550
Guido van Rossum141f7672007-04-10 00:22:16 +0000551
552class RawIOBase(IOBase):
553
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000554 """Base class for raw binary I/O."""
Guido van Rossum141f7672007-04-10 00:22:16 +0000555
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000556 # The read() method is implemented by calling readinto(); derived
557 # classes that want to support read() only need to implement
558 # readinto() as a primitive operation. In general, readinto() can be
559 # more efficient than read().
Guido van Rossum141f7672007-04-10 00:22:16 +0000560
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000561 # (It would be tempting to also provide an implementation of
562 # readinto() in terms of read(), in case the latter is a more suitable
563 # primitive operation, but that would lead to nasty recursion in case
564 # a subclass doesn't implement either.)
Guido van Rossum141f7672007-04-10 00:22:16 +0000565
Guido van Rossum7165cb12007-07-10 06:54:34 +0000566 def read(self, n: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000567 """Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000568
Georg Brandlf91197c2008-04-09 07:33:01 +0000569 Returns an empty bytes object on EOF, or None if the object is
Guido van Rossum01a27522007-03-07 01:00:12 +0000570 set not to block and has no data to read.
571 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000572 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000573 if n is None:
574 n = -1
575 if n < 0:
576 return self.readall()
Guido van Rossum254348e2007-11-21 19:29:53 +0000577 b = bytearray(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000578 n = self.readinto(b)
579 del b[n:]
Guido van Rossum98297ee2007-11-06 21:34:58 +0000580 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000581
Guido van Rossum7165cb12007-07-10 06:54:34 +0000582 def readall(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000583 """Read until EOF, using multiple read() call."""
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000584 self._checkClosed()
Guido van Rossum254348e2007-11-21 19:29:53 +0000585 res = bytearray()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000586 while True:
587 data = self.read(DEFAULT_BUFFER_SIZE)
588 if not data:
589 break
590 res += data
Guido van Rossum98297ee2007-11-06 21:34:58 +0000591 return bytes(res)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000592
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000593 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000594 """Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000595
596 Returns number of bytes read (0 for EOF), or None if the object
597 is set not to block as has no data to read.
598 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000599 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000600
Guido van Rossum141f7672007-04-10 00:22:16 +0000601 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000602 """Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000603
Guido van Rossum78892e42007-04-06 17:31:18 +0000604 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000605 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000606 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000607
Guido van Rossum78892e42007-04-06 17:31:18 +0000608
Guido van Rossum141f7672007-04-10 00:22:16 +0000609class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000610
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000611 """Raw I/O implementation for OS files."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000612
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000613 # This multiply inherits from _FileIO and RawIOBase to make
614 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
615 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
616 # to do since _fileio.c is written in C).
Guido van Rossuma9e20242007-03-08 00:43:48 +0000617
Barry Warsaw40e82462008-11-20 20:14:50 +0000618 def __init__(self, name, mode="r", closefd=True):
619 _fileio._FileIO.__init__(self, name, mode, closefd)
620 self._name = name
621
Guido van Rossum87429772007-04-10 21:06:59 +0000622 def close(self):
623 _fileio._FileIO.close(self)
624 RawIOBase.close(self)
625
Guido van Rossum13633bb2007-04-13 18:42:35 +0000626 @property
627 def name(self):
628 return self._name
629
Guido van Rossuma9e20242007-03-08 00:43:48 +0000630
Guido van Rossumcce92b22007-04-10 14:41:39 +0000631class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000632
633 """Base class for buffered IO objects.
634
635 The main difference with RawIOBase is that the read() method
636 supports omitting the size argument, and does not have a default
637 implementation that defers to readinto().
638
639 In addition, read(), readinto() and write() may raise
640 BlockingIOError if the underlying raw stream is in non-blocking
641 mode and not ready; unlike their raw counterparts, they will never
642 return None.
643
644 A typical implementation should not inherit from a RawIOBase
645 implementation, but wrap one.
646 """
647
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000648 def read(self, n: int = None) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000649 """Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000650
Guido van Rossum024da5c2007-05-17 23:59:11 +0000651 If the argument is omitted, None, or negative, reads and
652 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000653
654 If the argument is positive, and the underlying raw stream is
655 not 'interactive', multiple raw reads may be issued to satisfy
656 the byte count (unless EOF is reached first). But for
657 interactive raw streams (XXX and for pipes?), at most one raw
658 read will be issued, and a short result does not imply that
659 EOF is imminent.
660
661 Returns an empty bytes array on EOF.
662
663 Raises BlockingIOError if the underlying raw stream has no
664 data at the moment.
665 """
666 self._unsupported("read")
667
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000668 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000669 """Read up to len(b) bytes into b.
Guido van Rossum141f7672007-04-10 00:22:16 +0000670
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000671 Like read(), this may issue multiple reads to the underlying raw
672 stream, unless the latter is 'interactive'.
Guido van Rossum141f7672007-04-10 00:22:16 +0000673
674 Returns the number of bytes read (0 for EOF).
675
676 Raises BlockingIOError if the underlying raw stream has no
677 data at the moment.
678 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000679 # XXX This ought to work with anything that supports the buffer API
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000680 self._checkClosed()
Guido van Rossum87429772007-04-10 21:06:59 +0000681 data = self.read(len(b))
682 n = len(data)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000683 try:
684 b[:n] = data
685 except TypeError as err:
686 import array
687 if not isinstance(b, array.array):
688 raise err
689 b[:n] = array.array('b', data)
Guido van Rossum87429772007-04-10 21:06:59 +0000690 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000691
692 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000693 """Write the given buffer to the IO stream.
Guido van Rossum141f7672007-04-10 00:22:16 +0000694
Christian Heimes5d8da202008-05-06 13:58:24 +0000695 Return the number of bytes written, which is never less than
Guido van Rossum141f7672007-04-10 00:22:16 +0000696 len(b).
697
698 Raises BlockingIOError if the buffer is full and the
699 underlying raw stream cannot accept more data at the moment.
700 """
701 self._unsupported("write")
702
703
704class _BufferedIOMixin(BufferedIOBase):
705
706 """A mixin implementation of BufferedIOBase with an underlying raw stream.
707
708 This passes most requests on to the underlying raw stream. It
709 does *not* provide implementations of read(), readinto() or
710 write().
711 """
712
713 def __init__(self, raw):
714 self.raw = raw
715
716 ### Positioning ###
717
718 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000719 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000720
721 def tell(self):
722 return self.raw.tell()
723
724 def truncate(self, pos=None):
Guido van Rossum79b79ee2007-10-25 23:21:03 +0000725 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
726 # and a flush may be necessary to synch both views of the current
727 # file state.
728 self.flush()
Guido van Rossum57233cb2007-10-26 17:19:33 +0000729
730 if pos is None:
731 pos = self.tell()
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000732 # XXX: Should seek() be used, instead of passing the position
733 # XXX directly to truncate?
Guido van Rossum57233cb2007-10-26 17:19:33 +0000734 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000735
736 ### Flush and close ###
737
738 def flush(self):
739 self.raw.flush()
740
741 def close(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000742 if not self.closed:
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000743 try:
744 self.flush()
745 except IOError:
746 pass # If flush() fails, just give up
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000747 self.raw.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000748
749 ### Inquiries ###
750
751 def seekable(self):
752 return self.raw.seekable()
753
754 def readable(self):
755 return self.raw.readable()
756
757 def writable(self):
758 return self.raw.writable()
759
760 @property
761 def closed(self):
762 return self.raw.closed
763
Barry Warsaw40e82462008-11-20 20:14:50 +0000764 @property
765 def name(self):
766 return self.raw.name
767
768 @property
769 def mode(self):
770 return self.raw.mode
771
Guido van Rossum141f7672007-04-10 00:22:16 +0000772 ### Lower-level APIs ###
773
774 def fileno(self):
775 return self.raw.fileno()
776
777 def isatty(self):
778 return self.raw.isatty()
779
780
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000781class _BytesIO(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000782
Guido van Rossum024da5c2007-05-17 23:59:11 +0000783 """Buffered I/O implementation using an in-memory bytes buffer."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000784
Guido van Rossum024da5c2007-05-17 23:59:11 +0000785 def __init__(self, initial_bytes=None):
Guido van Rossum254348e2007-11-21 19:29:53 +0000786 buf = bytearray()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000787 if initial_bytes is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000788 buf += initial_bytes
789 self._buffer = buf
Guido van Rossum28524c72007-02-27 05:47:44 +0000790 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000791
792 def getvalue(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000793 """Return the bytes value (contents) of the buffer
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000794 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000795 self._checkClosed()
Guido van Rossum98297ee2007-11-06 21:34:58 +0000796 return bytes(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000797
Guido van Rossum024da5c2007-05-17 23:59:11 +0000798 def read(self, n=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000799 self._checkClosed()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000800 if n is None:
801 n = -1
Guido van Rossum141f7672007-04-10 00:22:16 +0000802 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000803 n = len(self._buffer)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000804 if len(self._buffer) <= self._pos:
Alexandre Vassalotti2e0419d2008-05-07 00:09:04 +0000805 return b""
Guido van Rossum28524c72007-02-27 05:47:44 +0000806 newpos = min(len(self._buffer), self._pos + n)
807 b = self._buffer[self._pos : newpos]
808 self._pos = newpos
Guido van Rossum98297ee2007-11-06 21:34:58 +0000809 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000810
Guido van Rossum024da5c2007-05-17 23:59:11 +0000811 def read1(self, n):
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000812 """This is the same as read.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000813 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000814 return self.read(n)
815
Guido van Rossum28524c72007-02-27 05:47:44 +0000816 def write(self, b):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000817 self._checkClosed()
Guido van Rossuma74184e2007-08-29 04:05:57 +0000818 if isinstance(b, str):
819 raise TypeError("can't write str to binary stream")
Guido van Rossum28524c72007-02-27 05:47:44 +0000820 n = len(b)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000821 if n == 0:
822 return 0
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000823 pos = self._pos
824 if pos > len(self._buffer):
Guido van Rossumb972a782007-07-21 00:25:15 +0000825 # Inserts null bytes between the current end of the file
826 # and the new write position.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000827 padding = b'\x00' * (pos - len(self._buffer))
828 self._buffer += padding
829 self._buffer[pos:pos + n] = b
830 self._pos += n
Guido van Rossum28524c72007-02-27 05:47:44 +0000831 return n
832
833 def seek(self, pos, whence=0):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000834 self._checkClosed()
Christian Heimes3ab4f652007-11-09 01:27:29 +0000835 try:
836 pos = pos.__index__()
837 except AttributeError as err:
838 raise TypeError("an integer is required") from err
Guido van Rossum28524c72007-02-27 05:47:44 +0000839 if whence == 0:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000840 if pos < 0:
841 raise ValueError("negative seek position %r" % (pos,))
Alexandre Vassalottif0c0ff62008-05-09 21:21:21 +0000842 self._pos = pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000843 elif whence == 1:
844 self._pos = max(0, self._pos + pos)
845 elif whence == 2:
846 self._pos = max(0, len(self._buffer) + pos)
847 else:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000848 raise ValueError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000849 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000850
851 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000852 self._checkClosed()
Guido van Rossum28524c72007-02-27 05:47:44 +0000853 return self._pos
854
855 def truncate(self, pos=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000856 self._checkClosed()
Guido van Rossum28524c72007-02-27 05:47:44 +0000857 if pos is None:
858 pos = self._pos
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000859 elif pos < 0:
860 raise ValueError("negative truncate position %r" % (pos,))
Guido van Rossum28524c72007-02-27 05:47:44 +0000861 del self._buffer[pos:]
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000862 return self.seek(pos)
Guido van Rossum28524c72007-02-27 05:47:44 +0000863
864 def readable(self):
865 return True
866
867 def writable(self):
868 return True
869
870 def seekable(self):
871 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000872
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000873# Use the faster implementation of BytesIO if available
874try:
875 import _bytesio
876
877 class BytesIO(_bytesio._BytesIO, BufferedIOBase):
878 __doc__ = _bytesio._BytesIO.__doc__
879
880except ImportError:
881 BytesIO = _BytesIO
882
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000883
Guido van Rossum141f7672007-04-10 00:22:16 +0000884class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000885
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000886 """BufferedReader(raw[, buffer_size])
887
888 A buffer for a readable, sequential BaseRawIO object.
889
890 The constructor creates a BufferedReader for the given readable raw
891 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
892 is used.
893 """
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000894
Guido van Rossum78892e42007-04-06 17:31:18 +0000895 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000896 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000897 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000898 raw._checkReadable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000899 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum78892e42007-04-06 17:31:18 +0000900 self.buffer_size = buffer_size
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000901 self._reset_read_buf()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +0000902 self._read_lock = Lock()
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000903
904 def _reset_read_buf(self):
905 self._read_buf = b""
906 self._read_pos = 0
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000907
Guido van Rossum024da5c2007-05-17 23:59:11 +0000908 def read(self, n=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000909 """Read n bytes.
910
911 Returns exactly n bytes of data unless the underlying raw IO
Walter Dörwalda3270002007-05-29 19:13:29 +0000912 stream reaches EOF or if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000913 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000914 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000915 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000916 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +0000917 with self._read_lock:
918 return self._read_unlocked(n)
919
920 def _read_unlocked(self, n=None):
Guido van Rossum78892e42007-04-06 17:31:18 +0000921 nodata_val = b""
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000922 empty_values = (b"", None)
923 buf = self._read_buf
924 pos = self._read_pos
925
926 # Special case for when the number of bytes to read is unspecified.
927 if n is None or n == -1:
928 self._reset_read_buf()
929 chunks = [buf[pos:]] # Strip the consumed bytes.
930 current_size = 0
931 while True:
932 # Read until EOF or until read() would block.
933 chunk = self.raw.read()
934 if chunk in empty_values:
935 nodata_val = chunk
936 break
937 current_size += len(chunk)
938 chunks.append(chunk)
939 return b"".join(chunks) or nodata_val
940
941 # The number of bytes to read is specified, return at most n bytes.
942 avail = len(buf) - pos # Length of the available buffered data.
943 if n <= avail:
944 # Fast path: the data to read is fully buffered.
945 self._read_pos += n
946 return buf[pos:pos+n]
947 # Slow path: read from the stream until enough bytes are read,
948 # or until an EOF occurs or until read() would block.
949 chunks = [buf[pos:]]
950 wanted = max(self.buffer_size, n)
951 while avail < n:
952 chunk = self.raw.read(wanted)
953 if chunk in empty_values:
954 nodata_val = chunk
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000955 break
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000956 avail += len(chunk)
957 chunks.append(chunk)
958 # n is more then avail only when an EOF occurred or when
959 # read() would have blocked.
960 n = min(n, avail)
961 out = b"".join(chunks)
962 self._read_buf = out[n:] # Save the extra data in the buffer.
963 self._read_pos = 0
964 return out[:n] if out else nodata_val
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000965
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000966 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000967 """Returns buffered bytes without advancing the position.
968
969 The argument indicates a desired minimal number of bytes; we
970 do at most one raw read to satisfy it. We never return more
971 than self.buffer_size.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000972 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000973 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +0000974 with self._read_lock:
975 return self._peek_unlocked(n)
976
977 def _peek_unlocked(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000978 want = min(n, self.buffer_size)
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000979 have = len(self._read_buf) - self._read_pos
Guido van Rossum13633bb2007-04-13 18:42:35 +0000980 if have < want:
981 to_read = self.buffer_size - have
982 current = self.raw.read(to_read)
983 if current:
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000984 self._read_buf = self._read_buf[self._read_pos:] + current
985 self._read_pos = 0
986 return self._read_buf[self._read_pos:]
Guido van Rossum13633bb2007-04-13 18:42:35 +0000987
988 def read1(self, n):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000989 """Reads up to n bytes, with at most one read() system call."""
990 # Returns up to n bytes. If at least one byte is buffered, we
991 # only return buffered bytes. Otherwise, we do one raw read.
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000992 self._checkClosed()
Guido van Rossum13633bb2007-04-13 18:42:35 +0000993 if n <= 0:
994 return b""
Antoine Pitrou87695762008-08-14 22:44:29 +0000995 with self._read_lock:
996 self._peek_unlocked(1)
997 return self._read_unlocked(
998 min(n, len(self._read_buf) - self._read_pos))
Guido van Rossum13633bb2007-04-13 18:42:35 +0000999
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001000 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001001 self._checkClosed()
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001002 return self.raw.tell() - len(self._read_buf) + self._read_pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001003
1004 def seek(self, pos, whence=0):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001005 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +00001006 with self._read_lock:
1007 if whence == 1:
1008 pos -= len(self._read_buf) - self._read_pos
1009 pos = self.raw.seek(pos, whence)
1010 self._reset_read_buf()
1011 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001012
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001013
Guido van Rossum141f7672007-04-10 00:22:16 +00001014class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001015
Christian Heimes5d8da202008-05-06 13:58:24 +00001016 """A buffer for a writeable sequential RawIO object.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001017
1018 The constructor creates a BufferedWriter for the given writeable raw
1019 stream. If the buffer_size is not given, it defaults to
1020 DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
1021 twice the buffer size.
1022 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001023
Guido van Rossum141f7672007-04-10 00:22:16 +00001024 def __init__(self, raw,
1025 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001026 raw._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001027 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001028 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +00001029 self.max_buffer_size = (2*buffer_size
1030 if max_buffer_size is None
1031 else max_buffer_size)
Guido van Rossum254348e2007-11-21 19:29:53 +00001032 self._write_buf = bytearray()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +00001033 self._write_lock = Lock()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001034
1035 def write(self, b):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001036 self._checkClosed()
Guido van Rossuma74184e2007-08-29 04:05:57 +00001037 if isinstance(b, str):
1038 raise TypeError("can't write str to binary stream")
Antoine Pitrou87695762008-08-14 22:44:29 +00001039 with self._write_lock:
1040 # XXX we can implement some more tricks to try and avoid
1041 # partial writes
1042 if len(self._write_buf) > self.buffer_size:
1043 # We're full, so let's pre-flush the buffer
1044 try:
1045 self._flush_unlocked()
1046 except BlockingIOError as e:
1047 # We can't accept anything else.
1048 # XXX Why not just let the exception pass through?
1049 raise BlockingIOError(e.errno, e.strerror, 0)
1050 before = len(self._write_buf)
1051 self._write_buf.extend(b)
1052 written = len(self._write_buf) - before
1053 if len(self._write_buf) > self.buffer_size:
1054 try:
1055 self._flush_unlocked()
1056 except BlockingIOError as e:
1057 if len(self._write_buf) > self.max_buffer_size:
1058 # We've hit max_buffer_size. We have to accept a
1059 # partial write and cut back our buffer.
1060 overage = len(self._write_buf) - self.max_buffer_size
1061 self._write_buf = self._write_buf[:self.max_buffer_size]
1062 raise BlockingIOError(e.errno, e.strerror, overage)
1063 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001064
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001065 def truncate(self, pos=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001066 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +00001067 with self._write_lock:
1068 self._flush_unlocked()
1069 if pos is None:
1070 pos = self.raw.tell()
1071 return self.raw.truncate(pos)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001072
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001073 def flush(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001074 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +00001075 with self._write_lock:
1076 self._flush_unlocked()
1077
1078 def _flush_unlocked(self):
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001079 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +00001080 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001081 while self._write_buf:
1082 n = self.raw.write(self._write_buf)
1083 del self._write_buf[:n]
1084 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001085 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001086 n = e.characters_written
1087 del self._write_buf[:n]
1088 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001089 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001090
1091 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001092 self._checkClosed()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001093 return self.raw.tell() + len(self._write_buf)
1094
1095 def seek(self, pos, whence=0):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001096 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +00001097 with self._write_lock:
1098 self._flush_unlocked()
1099 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001100
Guido van Rossum01a27522007-03-07 01:00:12 +00001101
Guido van Rossum141f7672007-04-10 00:22:16 +00001102class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001103
Guido van Rossum01a27522007-03-07 01:00:12 +00001104 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001105
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001106 A buffered reader object and buffered writer object put together to
1107 form a sequential IO object that can read and write. This is typically
1108 used with a socket or two-way pipe.
Guido van Rossum78892e42007-04-06 17:31:18 +00001109
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001110 reader and writer are RawIOBase objects that are readable and
1111 writeable respectively. If the buffer_size is omitted it defaults to
1112 DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
1113 defaults to twice the buffer size.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001114 """
1115
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001116 # XXX The usefulness of this (compared to having two separate IO
1117 # objects) is questionable.
1118
Guido van Rossum141f7672007-04-10 00:22:16 +00001119 def __init__(self, reader, writer,
1120 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1121 """Constructor.
1122
1123 The arguments are two RawIO instances.
1124 """
Guido van Rossum5abbf752007-08-27 17:39:33 +00001125 reader._checkReadable()
1126 writer._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001127 self.reader = BufferedReader(reader, buffer_size)
1128 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001129
Guido van Rossum024da5c2007-05-17 23:59:11 +00001130 def read(self, n=None):
1131 if n is None:
1132 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001133 return self.reader.read(n)
1134
Guido van Rossum141f7672007-04-10 00:22:16 +00001135 def readinto(self, b):
1136 return self.reader.readinto(b)
1137
Guido van Rossum01a27522007-03-07 01:00:12 +00001138 def write(self, b):
1139 return self.writer.write(b)
1140
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001141 def peek(self, n=0):
1142 return self.reader.peek(n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001143
1144 def read1(self, n):
1145 return self.reader.read1(n)
1146
Guido van Rossum01a27522007-03-07 01:00:12 +00001147 def readable(self):
1148 return self.reader.readable()
1149
1150 def writable(self):
1151 return self.writer.writable()
1152
1153 def flush(self):
1154 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001155
Guido van Rossum01a27522007-03-07 01:00:12 +00001156 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +00001157 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +00001158 self.reader.close()
1159
1160 def isatty(self):
1161 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +00001162
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001163 @property
1164 def closed(self):
Benjamin Peterson92035012008-12-27 16:00:54 +00001165 return self.writer.closed
Guido van Rossum01a27522007-03-07 01:00:12 +00001166
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001167
Guido van Rossum141f7672007-04-10 00:22:16 +00001168class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +00001169
Christian Heimes5d8da202008-05-06 13:58:24 +00001170 """A buffered interface to random access streams.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001171
1172 The constructor creates a reader and writer for a seekable stream,
1173 raw, given in the first argument. If the buffer_size is omitted it
1174 defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
1175 writer) defaults to twice the buffer size.
1176 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001177
Guido van Rossum141f7672007-04-10 00:22:16 +00001178 def __init__(self, raw,
1179 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001180 raw._checkSeekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001181 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001182 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1183
Guido van Rossum01a27522007-03-07 01:00:12 +00001184 def seek(self, pos, whence=0):
1185 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001186 # First do the raw seek, then empty the read buffer, so that
1187 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +00001188 pos = self.raw.seek(pos, whence)
Antoine Pitrou87695762008-08-14 22:44:29 +00001189 with self._read_lock:
1190 self._reset_read_buf()
Guido van Rossum53807da2007-04-10 19:01:47 +00001191 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +00001192
1193 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001194 self._checkClosed()
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001195 if self._write_buf:
Guido van Rossum01a27522007-03-07 01:00:12 +00001196 return self.raw.tell() + len(self._write_buf)
1197 else:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001198 return BufferedReader.tell(self)
Guido van Rossum01a27522007-03-07 01:00:12 +00001199
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001200 def truncate(self, pos=None):
1201 if pos is None:
1202 pos = self.tell()
1203 # Use seek to flush the read buffer.
1204 self.seek(pos)
1205 return BufferedWriter.truncate(self)
1206
Guido van Rossum024da5c2007-05-17 23:59:11 +00001207 def read(self, n=None):
1208 if n is None:
1209 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001210 self.flush()
1211 return BufferedReader.read(self, n)
1212
Guido van Rossum141f7672007-04-10 00:22:16 +00001213 def readinto(self, b):
1214 self.flush()
1215 return BufferedReader.readinto(self, b)
1216
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001217 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +00001218 self.flush()
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001219 return BufferedReader.peek(self, n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001220
1221 def read1(self, n):
1222 self.flush()
1223 return BufferedReader.read1(self, n)
1224
Guido van Rossum01a27522007-03-07 01:00:12 +00001225 def write(self, b):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001226 self._checkClosed()
Guido van Rossum78892e42007-04-06 17:31:18 +00001227 if self._read_buf:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001228 # Undo readahead
Antoine Pitrou87695762008-08-14 22:44:29 +00001229 with self._read_lock:
1230 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1231 self._reset_read_buf()
Guido van Rossum01a27522007-03-07 01:00:12 +00001232 return BufferedWriter.write(self, b)
1233
Guido van Rossum78892e42007-04-06 17:31:18 +00001234
Guido van Rossumcce92b22007-04-10 14:41:39 +00001235class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +00001236
1237 """Base class for text I/O.
1238
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001239 This class provides a character and line based interface to stream
1240 I/O. There is no readinto method because Python's character strings
1241 are immutable. There is no public constructor.
Guido van Rossum78892e42007-04-06 17:31:18 +00001242 """
1243
1244 def read(self, n: int = -1) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001245 """Read at most n characters from stream.
Guido van Rossum78892e42007-04-06 17:31:18 +00001246
1247 Read from underlying buffer until we have n characters or we hit EOF.
1248 If n is negative or omitted, read until EOF.
1249 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001250 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +00001251
Guido van Rossum9b76da62007-04-11 01:09:03 +00001252 def write(self, s: str) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001253 """Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001254 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +00001255
Guido van Rossum9b76da62007-04-11 01:09:03 +00001256 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001257 """Truncate size to pos."""
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001258 self._unsupported("truncate")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001259
Guido van Rossum78892e42007-04-06 17:31:18 +00001260 def readline(self) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001261 """Read until newline or EOF.
Guido van Rossum78892e42007-04-06 17:31:18 +00001262
1263 Returns an empty string if EOF is hit immediately.
1264 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001265 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +00001266
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001267 @property
1268 def encoding(self):
1269 """Subclasses should override."""
1270 return None
1271
Guido van Rossum8358db22007-08-18 21:39:55 +00001272 @property
1273 def newlines(self):
Christian Heimes5d8da202008-05-06 13:58:24 +00001274 """Line endings translated so far.
Guido van Rossum8358db22007-08-18 21:39:55 +00001275
1276 Only line endings translated during reading are considered.
1277
1278 Subclasses should override.
1279 """
1280 return None
1281
Guido van Rossum78892e42007-04-06 17:31:18 +00001282
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001283class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001284 r"""Codec used when reading a file in universal newlines mode. It wraps
1285 another incremental decoder, translating \r\n and \r into \n. It also
1286 records the types of newlines encountered. When used with
1287 translate=False, it ensures that the newline sequence is returned in
1288 one piece.
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001289 """
1290 def __init__(self, decoder, translate, errors='strict'):
1291 codecs.IncrementalDecoder.__init__(self, errors=errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001292 self.translate = translate
1293 self.decoder = decoder
1294 self.seennl = 0
Antoine Pitrou180a3362008-12-14 16:36:46 +00001295 self.pendingcr = False
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001296
1297 def decode(self, input, final=False):
1298 # decode input (with the eventual \r from a previous pass)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001299 output = self.decoder.decode(input, final=final)
Antoine Pitrou180a3362008-12-14 16:36:46 +00001300 if self.pendingcr and (output or final):
1301 output = "\r" + output
1302 self.pendingcr = False
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001303
1304 # retain last \r even when not translating data:
1305 # then readline() is sure to get \r\n in one pass
1306 if output.endswith("\r") and not final:
1307 output = output[:-1]
Antoine Pitrou180a3362008-12-14 16:36:46 +00001308 self.pendingcr = True
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001309
1310 # Record which newlines are read
1311 crlf = output.count('\r\n')
1312 cr = output.count('\r') - crlf
1313 lf = output.count('\n') - crlf
1314 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1315 | (crlf and self._CRLF)
1316
1317 if self.translate:
1318 if crlf:
1319 output = output.replace("\r\n", "\n")
1320 if cr:
1321 output = output.replace("\r", "\n")
1322
1323 return output
1324
1325 def getstate(self):
1326 buf, flag = self.decoder.getstate()
Antoine Pitrou180a3362008-12-14 16:36:46 +00001327 flag <<= 1
1328 if self.pendingcr:
1329 flag |= 1
1330 return buf, flag
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001331
1332 def setstate(self, state):
1333 buf, flag = state
Antoine Pitrou180a3362008-12-14 16:36:46 +00001334 self.pendingcr = bool(flag & 1)
1335 self.decoder.setstate((buf, flag >> 1))
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001336
1337 def reset(self):
Alexandre Vassalottic3d7fe02007-12-28 01:24:22 +00001338 self.seennl = 0
Antoine Pitrou180a3362008-12-14 16:36:46 +00001339 self.pendingcr = False
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001340 self.decoder.reset()
1341
1342 _LF = 1
1343 _CR = 2
1344 _CRLF = 4
1345
1346 @property
1347 def newlines(self):
1348 return (None,
1349 "\n",
1350 "\r",
1351 ("\r", "\n"),
1352 "\r\n",
1353 ("\n", "\r\n"),
1354 ("\r", "\r\n"),
1355 ("\r", "\n", "\r\n")
1356 )[self.seennl]
1357
1358
Guido van Rossum78892e42007-04-06 17:31:18 +00001359class TextIOWrapper(TextIOBase):
1360
Christian Heimes5d8da202008-05-06 13:58:24 +00001361 r"""Character and line based layer over a BufferedIOBase object, buffer.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001362
1363 encoding gives the name of the encoding that the stream will be
1364 decoded or encoded with. It defaults to locale.getpreferredencoding.
1365
1366 errors determines the strictness of encoding and decoding (see the
1367 codecs.register) and defaults to "strict".
1368
1369 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1370 handling of line endings. If it is None, universal newlines is
1371 enabled. With this enabled, on input, the lines endings '\n', '\r',
1372 or '\r\n' are translated to '\n' before being returned to the
1373 caller. Conversely, on output, '\n' is translated to the system
Mark Dickinson934896d2009-02-21 20:59:32 +00001374 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001375 legal values, that newline becomes the newline when the file is read
1376 and it is returned untranslated. On output, '\n' is converted to the
1377 newline.
1378
1379 If line_buffering is True, a call to flush is implied when a call to
1380 write contains a newline character.
Guido van Rossum78892e42007-04-06 17:31:18 +00001381 """
1382
Antoine Pitrou56b3a402008-12-15 23:01:43 +00001383 _CHUNK_SIZE = 2048
Guido van Rossum78892e42007-04-06 17:31:18 +00001384
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001385 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1386 line_buffering=False):
Guido van Rossum8358db22007-08-18 21:39:55 +00001387 if newline not in (None, "", "\n", "\r", "\r\n"):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001388 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +00001389 if encoding is None:
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001390 try:
1391 encoding = os.device_encoding(buffer.fileno())
Brett Cannon041683d2007-10-11 23:08:53 +00001392 except (AttributeError, UnsupportedOperation):
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001393 pass
1394 if encoding is None:
Martin v. Löwisd78d3b42007-08-11 15:36:45 +00001395 try:
1396 import locale
1397 except ImportError:
1398 # Importing locale may fail if Python is being built
1399 encoding = "ascii"
1400 else:
1401 encoding = locale.getpreferredencoding()
Guido van Rossum78892e42007-04-06 17:31:18 +00001402
Christian Heimes8bd14fb2007-11-08 16:34:32 +00001403 if not isinstance(encoding, str):
1404 raise ValueError("invalid encoding: %r" % encoding)
1405
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001406 if errors is None:
1407 errors = "strict"
1408 else:
1409 if not isinstance(errors, str):
1410 raise ValueError("invalid errors: %r" % errors)
1411
Guido van Rossum78892e42007-04-06 17:31:18 +00001412 self.buffer = buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001413 self._line_buffering = line_buffering
Guido van Rossum78892e42007-04-06 17:31:18 +00001414 self._encoding = encoding
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001415 self._errors = errors
Guido van Rossum8358db22007-08-18 21:39:55 +00001416 self._readuniversal = not newline
1417 self._readtranslate = newline is None
1418 self._readnl = newline
1419 self._writetranslate = newline != ''
1420 self._writenl = newline or os.linesep
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001421 self._encoder = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001422 self._decoder = None
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001423 self._decoded_chars = '' # buffer for text returned from decoder
1424 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001425 self._snapshot = None # info for reconstructing decoder state
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001426 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001427
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001428 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1429 # where dec_flags is the second (integer) item of the decoder state
1430 # and next_input is the chunk of input bytes that comes next after the
1431 # snapshot point. We use this to reconstruct decoder states in tell().
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001432
1433 # Naming convention:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001434 # - "bytes_..." for integer variables that count input bytes
1435 # - "chars_..." for integer variables that count decoded characters
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001436
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001437 @property
1438 def encoding(self):
1439 return self._encoding
1440
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001441 @property
1442 def errors(self):
1443 return self._errors
1444
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001445 @property
1446 def line_buffering(self):
1447 return self._line_buffering
1448
Ka-Ping Yeeddaa7062008-03-17 20:35:15 +00001449 def seekable(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001450 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +00001451
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001452 def readable(self):
1453 return self.buffer.readable()
1454
1455 def writable(self):
1456 return self.buffer.writable()
1457
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001458 def flush(self):
1459 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001460 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001461
1462 def close(self):
Guido van Rossum33e7a8e2007-07-22 20:38:07 +00001463 try:
1464 self.flush()
1465 except:
1466 pass # If flush() fails, just give up
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001467 self.buffer.close()
1468
1469 @property
1470 def closed(self):
1471 return self.buffer.closed
1472
Barry Warsaw40e82462008-11-20 20:14:50 +00001473 @property
1474 def name(self):
1475 return self.buffer.name
1476
Guido van Rossum9be55972007-04-07 02:59:27 +00001477 def fileno(self):
1478 return self.buffer.fileno()
1479
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001480 def isatty(self):
1481 return self.buffer.isatty()
1482
Guido van Rossum78892e42007-04-06 17:31:18 +00001483 def write(self, s: str):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001484 self._checkClosed()
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001485 if not isinstance(s, str):
Guido van Rossumdcce8392007-08-29 18:10:08 +00001486 raise TypeError("can't write %s to text stream" %
1487 s.__class__.__name__)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001488 length = len(s)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001489 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
Guido van Rossum8358db22007-08-18 21:39:55 +00001490 if haslf and self._writetranslate and self._writenl != "\n":
1491 s = s.replace("\n", self._writenl)
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001492 encoder = self._encoder or self._get_encoder()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001493 # XXX What if we were just reading?
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001494 b = encoder.encode(s)
Guido van Rossum8358db22007-08-18 21:39:55 +00001495 self.buffer.write(b)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001496 if self._line_buffering and (haslf or "\r" in s):
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001497 self.flush()
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001498 self._snapshot = None
1499 if self._decoder:
1500 self._decoder.reset()
1501 return length
Guido van Rossum78892e42007-04-06 17:31:18 +00001502
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001503 def _get_encoder(self):
1504 make_encoder = codecs.getincrementalencoder(self._encoding)
1505 self._encoder = make_encoder(self._errors)
1506 return self._encoder
1507
Guido van Rossum78892e42007-04-06 17:31:18 +00001508 def _get_decoder(self):
1509 make_decoder = codecs.getincrementaldecoder(self._encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001510 decoder = make_decoder(self._errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001511 if self._readuniversal:
1512 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1513 self._decoder = decoder
Guido van Rossum78892e42007-04-06 17:31:18 +00001514 return decoder
1515
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001516 # The following three methods implement an ADT for _decoded_chars.
1517 # Text returned from the decoder is buffered here until the client
1518 # requests it by calling our read() or readline() method.
1519 def _set_decoded_chars(self, chars):
1520 """Set the _decoded_chars buffer."""
1521 self._decoded_chars = chars
1522 self._decoded_chars_used = 0
1523
1524 def _get_decoded_chars(self, n=None):
1525 """Advance into the _decoded_chars buffer."""
1526 offset = self._decoded_chars_used
1527 if n is None:
1528 chars = self._decoded_chars[offset:]
1529 else:
1530 chars = self._decoded_chars[offset:offset + n]
1531 self._decoded_chars_used += len(chars)
1532 return chars
1533
1534 def _rewind_decoded_chars(self, n):
1535 """Rewind the _decoded_chars buffer."""
1536 if self._decoded_chars_used < n:
1537 raise AssertionError("rewind decoded_chars out of bounds")
1538 self._decoded_chars_used -= n
1539
Guido van Rossum9b76da62007-04-11 01:09:03 +00001540 def _read_chunk(self):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001541 """
1542 Read and decode the next chunk of data from the BufferedReader.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001543 """
1544
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001545 # The return value is True unless EOF was reached. The decoded
1546 # string is placed in self._decoded_chars (replacing its previous
1547 # value). The entire input chunk is sent to the decoder, though
1548 # some of it may remain buffered in the decoder, yet to be
1549 # converted.
1550
Guido van Rossum5abbf752007-08-27 17:39:33 +00001551 if self._decoder is None:
1552 raise ValueError("no decoder")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001553
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001554 if self._telling:
1555 # To prepare for tell(), we need to snapshot a point in the
1556 # file where the decoder's input buffer is empty.
Guido van Rossum9b76da62007-04-11 01:09:03 +00001557
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001558 dec_buffer, dec_flags = self._decoder.getstate()
1559 # Given this, we know there was a valid snapshot point
1560 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001561
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001562 # Read a chunk, decode it, and put the result in self._decoded_chars.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001563 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1564 eof = not input_chunk
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001565 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001566
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001567 if self._telling:
1568 # At the snapshot point, len(dec_buffer) bytes before the read,
1569 # the next input to be decoded is dec_buffer + input_chunk.
1570 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1571
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001572 return not eof
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001573
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001574 def _pack_cookie(self, position, dec_flags=0,
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001575 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001576 # The meaning of a tell() cookie is: seek to position, set the
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001577 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001578 # into the decoder with need_eof as the EOF flag, then skip
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001579 # chars_to_skip characters of the decoded result. For most simple
1580 # decoders, tell() will often just give a byte offset in the file.
1581 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1582 (chars_to_skip<<192) | bool(need_eof)<<256)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001583
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001584 def _unpack_cookie(self, bigint):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001585 rest, position = divmod(bigint, 1<<64)
1586 rest, dec_flags = divmod(rest, 1<<64)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001587 rest, bytes_to_feed = divmod(rest, 1<<64)
1588 need_eof, chars_to_skip = divmod(rest, 1<<64)
1589 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
Guido van Rossum9b76da62007-04-11 01:09:03 +00001590
1591 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001592 self._checkClosed()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001593 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001594 raise IOError("underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001595 if not self._telling:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001596 raise IOError("telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001597 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001598 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001599 decoder = self._decoder
1600 if decoder is None or self._snapshot is None:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001601 if self._decoded_chars:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001602 # This should never happen.
1603 raise AssertionError("pending decoded text")
Guido van Rossumcba608c2007-04-11 14:19:59 +00001604 return position
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001605
1606 # Skip backward to the snapshot point (see _read_chunk).
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001607 dec_flags, next_input = self._snapshot
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001608 position -= len(next_input)
1609
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001610 # How many decoded characters have been used up since the snapshot?
1611 chars_to_skip = self._decoded_chars_used
1612 if chars_to_skip == 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001613 # We haven't moved from the snapshot point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001614 return self._pack_cookie(position, dec_flags)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001615
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001616 # Starting from the snapshot position, we will walk the decoder
1617 # forward until it gives us enough decoded characters.
Guido van Rossumd76e7792007-04-17 02:38:04 +00001618 saved_state = decoder.getstate()
1619 try:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001620 # Note our initial start point.
1621 decoder.setstate((b'', dec_flags))
1622 start_pos = position
1623 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001624 need_eof = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001625
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001626 # Feed the decoder one byte at a time. As we go, note the
1627 # nearest "safe start point" before the current location
1628 # (a point where the decoder has nothing buffered, so seek()
1629 # can safely start from there and advance to this location).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001630 next_byte = bytearray(1)
1631 for next_byte[0] in next_input:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001632 bytes_fed += 1
1633 chars_decoded += len(decoder.decode(next_byte))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001634 dec_buffer, dec_flags = decoder.getstate()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001635 if not dec_buffer and chars_decoded <= chars_to_skip:
1636 # Decoder buffer is empty, so this is a safe start point.
1637 start_pos += bytes_fed
1638 chars_to_skip -= chars_decoded
1639 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1640 if chars_decoded >= chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001641 break
1642 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001643 # We didn't get enough decoded data; signal EOF to get more.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001644 chars_decoded += len(decoder.decode(b'', final=True))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001645 need_eof = 1
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001646 if chars_decoded < chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001647 raise IOError("can't reconstruct logical file position")
1648
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001649 # The returned cookie corresponds to the last safe start point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001650 return self._pack_cookie(
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001651 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001652 finally:
1653 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001654
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001655 def truncate(self, pos=None):
1656 self.flush()
1657 if pos is None:
1658 pos = self.tell()
1659 self.seek(pos)
1660 return self.buffer.truncate()
1661
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001662 def seek(self, cookie, whence=0):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001663 self._checkClosed()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001664 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001665 raise IOError("underlying stream is not seekable")
1666 if whence == 1: # seek relative to current position
1667 if cookie != 0:
1668 raise IOError("can't do nonzero cur-relative seeks")
1669 # Seeking to the current position should attempt to
1670 # sync the underlying buffer with the current position.
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001671 whence = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001672 cookie = self.tell()
1673 if whence == 2: # seek relative to end of file
1674 if cookie != 0:
1675 raise IOError("can't do nonzero end-relative seeks")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001676 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001677 position = self.buffer.seek(0, 2)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001678 self._set_decoded_chars('')
1679 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001680 if self._decoder:
1681 self._decoder.reset()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001682 return position
Guido van Rossum9b76da62007-04-11 01:09:03 +00001683 if whence != 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001684 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
Guido van Rossum9b76da62007-04-11 01:09:03 +00001685 (whence,))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001686 if cookie < 0:
1687 raise ValueError("negative seek position %r" % (cookie,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001688 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001689
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001690 # The strategy of seek() is to go back to the safe start point
1691 # and replay the effect of read(chars_to_skip) from there.
1692 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001693 self._unpack_cookie(cookie)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001694
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001695 # Seek back to the safe start point.
1696 self.buffer.seek(start_pos)
1697 self._set_decoded_chars('')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001698 self._snapshot = None
1699
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001700 # Restore the decoder to its state from the safe start point.
1701 if self._decoder or dec_flags or chars_to_skip:
1702 self._decoder = self._decoder or self._get_decoder()
1703 self._decoder.setstate((b'', dec_flags))
1704 self._snapshot = (dec_flags, b'')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001705
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001706 if chars_to_skip:
1707 # Just like _read_chunk, feed the decoder and save a snapshot.
1708 input_chunk = self.buffer.read(bytes_to_feed)
1709 self._set_decoded_chars(
1710 self._decoder.decode(input_chunk, need_eof))
1711 self._snapshot = (dec_flags, input_chunk)
1712
1713 # Skip chars_to_skip of the decoded characters.
1714 if len(self._decoded_chars) < chars_to_skip:
1715 raise IOError("can't restore logical file position")
1716 self._decoded_chars_used = chars_to_skip
1717
1718 return cookie
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001719
Guido van Rossum024da5c2007-05-17 23:59:11 +00001720 def read(self, n=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001721 self._checkClosed()
Guido van Rossum024da5c2007-05-17 23:59:11 +00001722 if n is None:
1723 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001724 decoder = self._decoder or self._get_decoder()
Guido van Rossum78892e42007-04-06 17:31:18 +00001725 if n < 0:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001726 # Read everything.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001727 result = (self._get_decoded_chars() +
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001728 decoder.decode(self.buffer.read(), final=True))
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001729 self._set_decoded_chars('')
1730 self._snapshot = None
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001731 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001732 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001733 # Keep reading chunks until we have n characters to return.
1734 eof = False
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001735 result = self._get_decoded_chars(n)
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001736 while len(result) < n and not eof:
1737 eof = not self._read_chunk()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001738 result += self._get_decoded_chars(n - len(result))
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001739 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001740
Guido van Rossum024da5c2007-05-17 23:59:11 +00001741 def __next__(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001742 self._checkClosed()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001743 self._telling = False
1744 line = self.readline()
1745 if not line:
1746 self._snapshot = None
1747 self._telling = self._seekable
1748 raise StopIteration
1749 return line
1750
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001751 def readline(self, limit=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001752 self._checkClosed()
Guido van Rossum98297ee2007-11-06 21:34:58 +00001753 if limit is None:
1754 limit = -1
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001755
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001756 # Grab all the decoded text (we will rewind any extra bits later).
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001757 line = self._get_decoded_chars()
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001758
Guido van Rossum78892e42007-04-06 17:31:18 +00001759 start = 0
1760 decoder = self._decoder or self._get_decoder()
1761
Guido van Rossum8358db22007-08-18 21:39:55 +00001762 pos = endpos = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001763 while True:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001764 if self._readtranslate:
1765 # Newlines are already translated, only search for \n
1766 pos = line.find('\n', start)
1767 if pos >= 0:
1768 endpos = pos + 1
1769 break
1770 else:
1771 start = len(line)
1772
1773 elif self._readuniversal:
Guido van Rossum8358db22007-08-18 21:39:55 +00001774 # Universal newline search. Find any of \r, \r\n, \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001775 # The decoder ensures that \r\n are not split in two pieces
Guido van Rossum78892e42007-04-06 17:31:18 +00001776
Guido van Rossum8358db22007-08-18 21:39:55 +00001777 # In C we'd look for these in parallel of course.
1778 nlpos = line.find("\n", start)
1779 crpos = line.find("\r", start)
1780 if crpos == -1:
1781 if nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001782 # Nothing found
Guido van Rossum8358db22007-08-18 21:39:55 +00001783 start = len(line)
Guido van Rossum78892e42007-04-06 17:31:18 +00001784 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001785 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001786 endpos = nlpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001787 break
1788 elif nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001789 # Found lone \r
1790 endpos = crpos + 1
1791 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001792 elif nlpos < crpos:
1793 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001794 endpos = nlpos + 1
Guido van Rossum78892e42007-04-06 17:31:18 +00001795 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001796 elif nlpos == crpos + 1:
1797 # Found \r\n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001798 endpos = crpos + 2
Guido van Rossum8358db22007-08-18 21:39:55 +00001799 break
1800 else:
1801 # Found \r
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001802 endpos = crpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001803 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001804 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001805 # non-universal
1806 pos = line.find(self._readnl)
1807 if pos >= 0:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001808 endpos = pos + len(self._readnl)
Guido van Rossum8358db22007-08-18 21:39:55 +00001809 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001810
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001811 if limit >= 0 and len(line) >= limit:
1812 endpos = limit # reached length limit
1813 break
1814
Guido van Rossum78892e42007-04-06 17:31:18 +00001815 # No line ending seen yet - get more data
Guido van Rossum8358db22007-08-18 21:39:55 +00001816 more_line = ''
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001817 while self._read_chunk():
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001818 if self._decoded_chars:
Guido van Rossum78892e42007-04-06 17:31:18 +00001819 break
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001820 if self._decoded_chars:
1821 line += self._get_decoded_chars()
Guido van Rossum8358db22007-08-18 21:39:55 +00001822 else:
1823 # end of file
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001824 self._set_decoded_chars('')
1825 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001826 return line
Guido van Rossum78892e42007-04-06 17:31:18 +00001827
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001828 if limit >= 0 and endpos > limit:
1829 endpos = limit # don't exceed limit
1830
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001831 # Rewind _decoded_chars to just after the line ending we found.
1832 self._rewind_decoded_chars(len(line) - endpos)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001833 return line[:endpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001834
Guido van Rossum8358db22007-08-18 21:39:55 +00001835 @property
1836 def newlines(self):
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001837 return self._decoder.newlines if self._decoder else None
Guido van Rossum024da5c2007-05-17 23:59:11 +00001838
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001839class _StringIO(TextIOWrapper):
1840 """Text I/O implementation using an in-memory buffer.
1841
1842 The initial_value argument sets the value of object. The newline
1843 argument is like the one of TextIOWrapper's constructor.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001844 """
Guido van Rossum024da5c2007-05-17 23:59:11 +00001845
1846 # XXX This is really slow, but fully functional
1847
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001848 def __init__(self, initial_value="", newline="\n"):
1849 super(_StringIO, self).__init__(BytesIO(),
1850 encoding="utf-8",
1851 errors="strict",
1852 newline=newline)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001853 if initial_value:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001854 if not isinstance(initial_value, str):
Guido van Rossum34d19282007-08-09 01:03:29 +00001855 initial_value = str(initial_value)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001856 self.write(initial_value)
1857 self.seek(0)
1858
1859 def getvalue(self):
Guido van Rossum34d19282007-08-09 01:03:29 +00001860 self.flush()
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001861 return self.buffer.getvalue().decode(self._encoding, self._errors)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001862
1863try:
1864 import _stringio
1865
1866 # This subclass is a reimplementation of the TextIOWrapper
1867 # interface without any of its text decoding facilities. All the
1868 # stored data is manipulated with the efficient
1869 # _stringio._StringIO extension type. Also, the newline decoding
1870 # mechanism of IncrementalNewlineDecoder is reimplemented here for
1871 # efficiency. Doing otherwise, would require us to implement a
1872 # fake decoder which would add an additional and unnecessary layer
1873 # on top of the _StringIO methods.
1874
1875 class StringIO(_stringio._StringIO, TextIOBase):
1876 """Text I/O implementation using an in-memory buffer.
1877
1878 The initial_value argument sets the value of object. The newline
1879 argument is like the one of TextIOWrapper's constructor.
1880 """
1881
1882 _CHUNK_SIZE = 4096
1883
1884 def __init__(self, initial_value="", newline="\n"):
1885 if newline not in (None, "", "\n", "\r", "\r\n"):
1886 raise ValueError("illegal newline value: %r" % (newline,))
1887
1888 self._readuniversal = not newline
1889 self._readtranslate = newline is None
1890 self._readnl = newline
1891 self._writetranslate = newline != ""
1892 self._writenl = newline or os.linesep
1893 self._pending = ""
1894 self._seennl = 0
1895
1896 # Reset the buffer first, in case __init__ is called
1897 # multiple times.
1898 self.truncate(0)
1899 if initial_value is None:
1900 initial_value = ""
1901 self.write(initial_value)
1902 self.seek(0)
1903
1904 @property
1905 def buffer(self):
1906 raise UnsupportedOperation("%s.buffer attribute is unsupported" %
1907 self.__class__.__name__)
1908
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +00001909 # XXX Cruft to support the TextIOWrapper API. This would only
1910 # be meaningful if StringIO supported the buffer attribute.
1911 # Hopefully, a better solution, than adding these pseudo-attributes,
1912 # will be found.
1913 @property
1914 def encoding(self):
1915 return "utf-8"
1916
1917 @property
1918 def errors(self):
1919 return "strict"
1920
1921 @property
1922 def line_buffering(self):
1923 return False
1924
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001925 def _decode_newlines(self, input, final=False):
1926 # decode input (with the eventual \r from a previous pass)
1927 if self._pending:
1928 input = self._pending + input
1929
1930 # retain last \r even when not translating data:
1931 # then readline() is sure to get \r\n in one pass
1932 if input.endswith("\r") and not final:
1933 input = input[:-1]
1934 self._pending = "\r"
1935 else:
1936 self._pending = ""
1937
1938 # Record which newlines are read
1939 crlf = input.count('\r\n')
1940 cr = input.count('\r') - crlf
1941 lf = input.count('\n') - crlf
1942 self._seennl |= (lf and self._LF) | (cr and self._CR) \
1943 | (crlf and self._CRLF)
1944
1945 if self._readtranslate:
1946 if crlf:
1947 output = input.replace("\r\n", "\n")
1948 if cr:
1949 output = input.replace("\r", "\n")
1950 else:
1951 output = input
1952
1953 return output
1954
1955 def writable(self):
1956 return True
1957
1958 def readable(self):
1959 return True
1960
1961 def seekable(self):
1962 return True
1963
1964 _read = _stringio._StringIO.read
1965 _write = _stringio._StringIO.write
1966 _tell = _stringio._StringIO.tell
1967 _seek = _stringio._StringIO.seek
1968 _truncate = _stringio._StringIO.truncate
1969 _getvalue = _stringio._StringIO.getvalue
1970
1971 def getvalue(self) -> str:
1972 """Retrieve the entire contents of the object."""
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001973 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001974 return self._getvalue()
1975
1976 def write(self, s: str) -> int:
1977 """Write string s to file.
1978
1979 Returns the number of characters written.
1980 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001981 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001982 if not isinstance(s, str):
1983 raise TypeError("can't write %s to text stream" %
1984 s.__class__.__name__)
1985 length = len(s)
1986 if self._writetranslate and self._writenl != "\n":
1987 s = s.replace("\n", self._writenl)
1988 self._pending = ""
1989 self._write(s)
1990 return length
1991
1992 def read(self, n: int = None) -> str:
1993 """Read at most n characters, returned as a string.
1994
1995 If the argument is negative or omitted, read until EOF
1996 is reached. Return an empty string at EOF.
1997 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001998 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001999 if n is None:
2000 n = -1
2001 res = self._pending
2002 if n < 0:
2003 res += self._decode_newlines(self._read(), True)
2004 self._pending = ""
2005 return res
2006 else:
2007 res = self._decode_newlines(self._read(n), True)
2008 self._pending = res[n:]
2009 return res[:n]
2010
2011 def tell(self) -> int:
2012 """Tell the current file position."""
Antoine Pitrou8043cf82009-01-09 19:54:29 +00002013 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002014 if self._pending:
2015 return self._tell() - len(self._pending)
2016 else:
2017 return self._tell()
2018
2019 def seek(self, pos: int = None, whence: int = 0) -> int:
2020 """Change stream position.
2021
2022 Seek to character offset pos relative to position indicated by whence:
2023 0 Start of stream (the default). pos should be >= 0;
2024 1 Current position - pos must be 0;
2025 2 End of stream - pos must be 0.
2026 Returns the new absolute position.
2027 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +00002028 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002029 self._pending = ""
2030 return self._seek(pos, whence)
2031
2032 def truncate(self, pos: int = None) -> int:
2033 """Truncate size to pos.
2034
2035 The pos argument defaults to the current file position, as
2036 returned by tell(). Imply an absolute seek to pos.
2037 Returns the new absolute position.
2038 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +00002039 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002040 self._pending = ""
2041 return self._truncate(pos)
2042
2043 def readline(self, limit: int = None) -> str:
Antoine Pitrou8043cf82009-01-09 19:54:29 +00002044 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002045 if limit is None:
2046 limit = -1
2047 if limit >= 0:
2048 # XXX: Hack to support limit argument, for backwards
2049 # XXX compatibility
2050 line = self.readline()
2051 if len(line) <= limit:
2052 return line
2053 line, self._pending = line[:limit], line[limit:] + self._pending
2054 return line
2055
2056 line = self._pending
2057 self._pending = ""
2058
2059 start = 0
2060 pos = endpos = None
2061 while True:
2062 if self._readtranslate:
2063 # Newlines are already translated, only search for \n
2064 pos = line.find('\n', start)
2065 if pos >= 0:
2066 endpos = pos + 1
2067 break
2068 else:
2069 start = len(line)
2070
2071 elif self._readuniversal:
2072 # Universal newline search. Find any of \r, \r\n, \n
2073 # The decoder ensures that \r\n are not split in two pieces
2074
2075 # In C we'd look for these in parallel of course.
2076 nlpos = line.find("\n", start)
2077 crpos = line.find("\r", start)
2078 if crpos == -1:
2079 if nlpos == -1:
2080 # Nothing found
2081 start = len(line)
2082 else:
2083 # Found \n
2084 endpos = nlpos + 1
2085 break
2086 elif nlpos == -1:
2087 # Found lone \r
2088 endpos = crpos + 1
2089 break
2090 elif nlpos < crpos:
2091 # Found \n
2092 endpos = nlpos + 1
2093 break
2094 elif nlpos == crpos + 1:
2095 # Found \r\n
2096 endpos = crpos + 2
2097 break
2098 else:
2099 # Found \r
2100 endpos = crpos + 1
2101 break
2102 else:
2103 # non-universal
2104 pos = line.find(self._readnl)
2105 if pos >= 0:
2106 endpos = pos + len(self._readnl)
2107 break
2108
2109 # No line ending seen yet - get more data
2110 more_line = self.read(self._CHUNK_SIZE)
2111 if more_line:
2112 line += more_line
2113 else:
2114 # end of file
2115 return line
2116
2117 self._pending = line[endpos:]
2118 return line[:endpos]
2119
2120 _LF = 1
2121 _CR = 2
2122 _CRLF = 4
2123
2124 @property
2125 def newlines(self):
2126 return (None,
2127 "\n",
2128 "\r",
2129 ("\r", "\n"),
2130 "\r\n",
2131 ("\n", "\r\n"),
2132 ("\r", "\r\n"),
2133 ("\r", "\n", "\r\n")
2134 )[self._seennl]
2135
2136
2137except ImportError:
2138 StringIO = _StringIO