blob: 439ca95adb1b207d270669cb31df9e787b75166b [file] [log] [blame]
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +00001"""The io module provides the Python interfaces to stream handling. The
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00002builtin open function is defined in this module.
3
4At the top of the I/O hierarchy is the abstract base class IOBase. It
5defines the basic interface to a stream. Note, however, that there is no
6seperation between reading and writing to streams; implementations are
7allowed to throw an IOError if they do not support a given operation.
8
9Extending IOBase is RawIOBase which deals simply with the reading and
10writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
11an interface to OS files.
12
13BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
14subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
15streams that are readable, writable, and both respectively.
16BufferedRandom provides a buffered interface to random access
17streams. BytesIO is a simple stream of in-memory bytes.
18
19Another IOBase subclass, TextIOBase, deals with the encoding and decoding
20of streams into text. TextIOWrapper, which extends it, is a buffered text
21interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
22is a in-memory stream for text.
23
24Argument names are not part of the specification, and only the arguments
25of open() are intended to be used as keyword arguments.
26
27data:
28
29DEFAULT_BUFFER_SIZE
30
31 An int containing the default buffer size used by the module's buffered
32 I/O classes. open() uses the file's blksize (as obtained by os.stat) if
33 possible.
34"""
35# New I/O library conforming to PEP 3116.
36
37# This is a prototype; hopefully eventually some of this will be
38# reimplemented in C.
39
40# XXX edge cases when switching between reading/writing
41# XXX need to support 1 meaning line-buffered
42# XXX whenever an argument is None, use the default value
43# XXX read/write ops should check readable/writable
44# XXX buffered readinto should work with arbitrary buffer objects
45# XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG
46# XXX check writable, readable and seekable in appropriate places
47
Guido van Rossum28524c72007-02-27 05:47:44 +000048
Guido van Rossum68bbcd22007-02-27 17:19:33 +000049__author__ = ("Guido van Rossum <guido@python.org>, "
Guido van Rossum78892e42007-04-06 17:31:18 +000050 "Mike Verdone <mike.verdone@gmail.com>, "
51 "Mark Russell <mark.russell@zen.co.uk>")
Guido van Rossum28524c72007-02-27 05:47:44 +000052
Guido van Rossum141f7672007-04-10 00:22:16 +000053__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
Guido van Rossum5abbf752007-08-27 17:39:33 +000054 "BytesIO", "StringIO", "BufferedIOBase",
Guido van Rossum01a27522007-03-07 01:00:12 +000055 "BufferedReader", "BufferedWriter", "BufferedRWPair",
Guido van Rossum141f7672007-04-10 00:22:16 +000056 "BufferedRandom", "TextIOBase", "TextIOWrapper"]
Guido van Rossum28524c72007-02-27 05:47:44 +000057
58import os
Guido van Rossumb7f136e2007-08-22 18:14:10 +000059import abc
Guido van Rossum78892e42007-04-06 17:31:18 +000060import codecs
Guido van Rossum141f7672007-04-10 00:22:16 +000061import _fileio
Christian Heimesdeb75f52008-08-15 18:43:03 +000062# Import _thread instead of threading to reduce startup cost
63try:
64 from _thread import allocate_lock as Lock
65except ImportError:
66 from _dummy_thread import allocate_lock as Lock
67
Guido van Rossum28524c72007-02-27 05:47:44 +000068
Guido van Rossum5abbf752007-08-27 17:39:33 +000069# open() uses st_blksize whenever we can
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000070DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
Guido van Rossum01a27522007-03-07 01:00:12 +000071
72
Guido van Rossum141f7672007-04-10 00:22:16 +000073class BlockingIOError(IOError):
Guido van Rossum78892e42007-04-06 17:31:18 +000074
Guido van Rossum141f7672007-04-10 00:22:16 +000075 """Exception raised when I/O would block on a non-blocking I/O stream."""
76
77 def __init__(self, errno, strerror, characters_written=0):
Guido van Rossum01a27522007-03-07 01:00:12 +000078 IOError.__init__(self, errno, strerror)
79 self.characters_written = characters_written
80
Guido van Rossum68bbcd22007-02-27 17:19:33 +000081
Guido van Rossume7fc50f2007-12-03 22:54:21 +000082def open(file, mode="r", buffering=None, encoding=None, errors=None,
83 newline=None, closefd=True):
Christian Heimes5d8da202008-05-06 13:58:24 +000084
Guido van Rossumf0af3e32008-10-02 18:55:37 +000085 r"""Open file and return a stream. Raise IOError upon failure.
Guido van Rossum17e43e52007-02-27 15:45:13 +000086
Guido van Rossumf0af3e32008-10-02 18:55:37 +000087 file is either a text or byte string giving the name (and the path
88 if the file isn't in the current working directory) of the file to
89 be opened or an integer file descriptor of the file to be
90 wrapped. (If a file descriptor is given, it is closed when the
91 returned I/O object is closed, unless closefd is set to False.)
Guido van Rossum8358db22007-08-18 21:39:55 +000092
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000093 mode is an optional string that specifies the mode in which the file
94 is opened. It defaults to 'r' which means open for reading in text
95 mode. Other common values are 'w' for writing (truncating the file if
96 it already exists), and 'a' for appending (which on some Unix systems,
97 means that all writes append to the end of the file regardless of the
98 current seek position). In text mode, if encoding is not specified the
99 encoding used is platform dependent. (For reading and writing raw
100 bytes use binary mode and leave encoding unspecified.) The available
101 modes are:
Guido van Rossum8358db22007-08-18 21:39:55 +0000102
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000103 ========= ===============================================================
104 Character Meaning
105 --------- ---------------------------------------------------------------
106 'r' open for reading (default)
107 'w' open for writing, truncating the file first
108 'a' open for writing, appending to the end of the file if it exists
109 'b' binary mode
110 't' text mode (default)
111 '+' open a disk file for updating (reading and writing)
112 'U' universal newline mode (for backwards compatibility; unneeded
113 for new code)
114 ========= ===============================================================
Guido van Rossum17e43e52007-02-27 15:45:13 +0000115
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000116 The default mode is 'rt' (open for reading text). For binary random
117 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
118 'r+b' opens the file without truncation.
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000119
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000120 Python distinguishes between files opened in binary and text modes,
121 even when the underlying operating system doesn't. Files opened in
122 binary mode (appending 'b' to the mode argument) return contents as
123 bytes objects without any decoding. In text mode (the default, or when
124 't' is appended to the mode argument), the contents of the file are
125 returned as strings, the bytes having been first decoded using a
126 platform-dependent encoding or using the specified encoding if given.
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000127
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000128 buffering is an optional integer used to set the buffering policy. By
129 default full buffering is on. Pass 0 to switch buffering off (only
130 allowed in binary mode), 1 to set line buffering, and an integer > 1
131 for full buffering.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000132
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000133 encoding is the name of the encoding used to decode or encode the
134 file. This should only be used in text mode. The default encoding is
135 platform dependent, but any encoding supported by Python can be
136 passed. See the codecs module for the list of supported encodings.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000137
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000138 errors is an optional string that specifies how encoding errors are to
139 be handled---this argument should not be used in binary mode. Pass
140 'strict' to raise a ValueError exception if there is an encoding error
141 (the default of None has the same effect), or pass 'ignore' to ignore
142 errors. (Note that ignoring encoding errors can lead to data loss.)
143 See the documentation for codecs.register for a list of the permitted
144 encoding error strings.
145
146 newline controls how universal newlines works (it only applies to text
147 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
148 follows:
149
150 * On input, if newline is None, universal newlines mode is
151 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
152 these are translated into '\n' before being returned to the
153 caller. If it is '', universal newline mode is enabled, but line
154 endings are returned to the caller untranslated. If it has any of
155 the other legal values, input lines are only terminated by the given
156 string, and the line ending is returned to the caller untranslated.
157
158 * On output, if newline is None, any '\n' characters written are
159 translated to the system default line separator, os.linesep. If
160 newline is '', no translation takes place. If newline is any of the
161 other legal values, any '\n' characters written are translated to
162 the given string.
163
164 If closefd is False, the underlying file descriptor will be kept open
165 when the file is closed. This does not work when a file name is given
166 and must be True in that case.
167
168 open() returns a file object whose type depends on the mode, and
169 through which the standard file operations such as reading and writing
170 are performed. When open() is used to open a file in a text mode ('w',
171 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
172 a file in a binary mode, the returned class varies: in read binary
173 mode, it returns a BufferedReader; in write binary and append binary
174 modes, it returns a BufferedWriter, and in read/write mode, it returns
175 a BufferedRandom.
176
177 It is also possible to use a string or bytearray as a file for both
178 reading and writing. For strings StringIO can be used like a file
179 opened in a text mode, and for bytes a BytesIO can be used like a file
180 opened in a binary mode.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000181 """
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000182 if not isinstance(file, (str, bytes, int)):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000183 raise TypeError("invalid file: %r" % file)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000184 if not isinstance(mode, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000185 raise TypeError("invalid mode: %r" % mode)
186 if buffering is not None and not isinstance(buffering, int):
187 raise TypeError("invalid buffering: %r" % buffering)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000188 if encoding is not None and not isinstance(encoding, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000189 raise TypeError("invalid encoding: %r" % encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000190 if errors is not None and not isinstance(errors, str):
191 raise TypeError("invalid errors: %r" % errors)
Guido van Rossum28524c72007-02-27 05:47:44 +0000192 modes = set(mode)
Guido van Rossum9be55972007-04-07 02:59:27 +0000193 if modes - set("arwb+tU") or len(mode) > len(modes):
Guido van Rossum28524c72007-02-27 05:47:44 +0000194 raise ValueError("invalid mode: %r" % mode)
195 reading = "r" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000196 writing = "w" in modes
Guido van Rossum28524c72007-02-27 05:47:44 +0000197 appending = "a" in modes
198 updating = "+" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000199 text = "t" in modes
200 binary = "b" in modes
Guido van Rossum7165cb12007-07-10 06:54:34 +0000201 if "U" in modes:
202 if writing or appending:
203 raise ValueError("can't use U and writing mode at once")
Guido van Rossum9be55972007-04-07 02:59:27 +0000204 reading = True
Guido van Rossum28524c72007-02-27 05:47:44 +0000205 if text and binary:
206 raise ValueError("can't have text and binary mode at once")
207 if reading + writing + appending > 1:
208 raise ValueError("can't have read/write/append mode at once")
209 if not (reading or writing or appending):
210 raise ValueError("must have exactly one of read/write/append mode")
211 if binary and encoding is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +0000212 raise ValueError("binary mode doesn't take an encoding argument")
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000213 if binary and errors is not None:
214 raise ValueError("binary mode doesn't take an errors argument")
Guido van Rossum9b76da62007-04-11 01:09:03 +0000215 if binary and newline is not None:
216 raise ValueError("binary mode doesn't take a newline argument")
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000217 raw = FileIO(file,
Guido van Rossum28524c72007-02-27 05:47:44 +0000218 (reading and "r" or "") +
219 (writing and "w" or "") +
220 (appending and "a" or "") +
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000221 (updating and "+" or ""),
222 closefd)
Guido van Rossum28524c72007-02-27 05:47:44 +0000223 if buffering is None:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000224 buffering = -1
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000225 line_buffering = False
226 if buffering == 1 or buffering < 0 and raw.isatty():
227 buffering = -1
228 line_buffering = True
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000229 if buffering < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000230 buffering = DEFAULT_BUFFER_SIZE
Guido van Rossum17e43e52007-02-27 15:45:13 +0000231 try:
232 bs = os.fstat(raw.fileno()).st_blksize
233 except (os.error, AttributeError):
Guido van Rossumbb09b212007-03-18 03:36:28 +0000234 pass
235 else:
Guido van Rossum17e43e52007-02-27 15:45:13 +0000236 if bs > 1:
237 buffering = bs
Guido van Rossum28524c72007-02-27 05:47:44 +0000238 if buffering < 0:
239 raise ValueError("invalid buffering size")
240 if buffering == 0:
241 if binary:
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().
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000494 self._checkClosed()
Guido van Rossum2bf71382007-06-08 00:07:57 +0000495 if hasattr(self, "peek"):
496 def nreadahead():
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000497 readahead = self.peek(1)
Guido van Rossum2bf71382007-06-08 00:07:57 +0000498 if not readahead:
499 return 1
500 n = (readahead.find(b"\n") + 1) or len(readahead)
501 if limit >= 0:
502 n = min(n, limit)
503 return n
504 else:
505 def nreadahead():
506 return 1
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000507 if limit is None:
508 limit = -1
Guido van Rossum254348e2007-11-21 19:29:53 +0000509 res = bytearray()
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000510 while limit < 0 or len(res) < limit:
Guido van Rossum2bf71382007-06-08 00:07:57 +0000511 b = self.read(nreadahead())
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000512 if not b:
513 break
514 res += b
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000515 if res.endswith(b"\n"):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000516 break
Guido van Rossum98297ee2007-11-06 21:34:58 +0000517 return bytes(res)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000518
Guido van Rossum7165cb12007-07-10 06:54:34 +0000519 def __iter__(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000520 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000521 return self
522
523 def __next__(self):
524 line = self.readline()
525 if not line:
526 raise StopIteration
527 return line
528
529 def readlines(self, hint=None):
Christian Heimes5d8da202008-05-06 13:58:24 +0000530 """Return a list of lines from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000531
532 hint can be specified to control the number of lines read: no more
533 lines will be read if the total size (in bytes/characters) of all
534 lines so far exceeds hint.
535 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000536 self._checkClosed()
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000537 if hint is None or hint <= 0:
Guido van Rossum7165cb12007-07-10 06:54:34 +0000538 return list(self)
539 n = 0
540 lines = []
541 for line in self:
542 lines.append(line)
543 n += len(line)
544 if n >= hint:
545 break
546 return lines
547
548 def writelines(self, lines):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000549 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000550 for line in lines:
551 self.write(line)
552
Guido van Rossum141f7672007-04-10 00:22:16 +0000553
554class RawIOBase(IOBase):
555
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000556 """Base class for raw binary I/O."""
Guido van Rossum141f7672007-04-10 00:22:16 +0000557
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000558 # The read() method is implemented by calling readinto(); derived
559 # classes that want to support read() only need to implement
560 # readinto() as a primitive operation. In general, readinto() can be
561 # more efficient than read().
Guido van Rossum141f7672007-04-10 00:22:16 +0000562
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000563 # (It would be tempting to also provide an implementation of
564 # readinto() in terms of read(), in case the latter is a more suitable
565 # primitive operation, but that would lead to nasty recursion in case
566 # a subclass doesn't implement either.)
Guido van Rossum141f7672007-04-10 00:22:16 +0000567
Guido van Rossum7165cb12007-07-10 06:54:34 +0000568 def read(self, n: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000569 """Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000570
Georg Brandlf91197c2008-04-09 07:33:01 +0000571 Returns an empty bytes object on EOF, or None if the object is
Guido van Rossum01a27522007-03-07 01:00:12 +0000572 set not to block and has no data to read.
573 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000574 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000575 if n is None:
576 n = -1
577 if n < 0:
578 return self.readall()
Guido van Rossum254348e2007-11-21 19:29:53 +0000579 b = bytearray(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000580 n = self.readinto(b)
581 del b[n:]
Guido van Rossum98297ee2007-11-06 21:34:58 +0000582 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000583
Guido van Rossum7165cb12007-07-10 06:54:34 +0000584 def readall(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000585 """Read until EOF, using multiple read() call."""
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000586 self._checkClosed()
Guido van Rossum254348e2007-11-21 19:29:53 +0000587 res = bytearray()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000588 while True:
589 data = self.read(DEFAULT_BUFFER_SIZE)
590 if not data:
591 break
592 res += data
Guido van Rossum98297ee2007-11-06 21:34:58 +0000593 return bytes(res)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000594
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000595 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000596 """Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000597
598 Returns number of bytes read (0 for EOF), or None if the object
599 is set not to block as has no data to read.
600 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000601 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000602
Guido van Rossum141f7672007-04-10 00:22:16 +0000603 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000604 """Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000605
Guido van Rossum78892e42007-04-06 17:31:18 +0000606 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000607 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000608 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000609
Guido van Rossum78892e42007-04-06 17:31:18 +0000610
Guido van Rossum141f7672007-04-10 00:22:16 +0000611class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000612
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000613 """Raw I/O implementation for OS files."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000614
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000615 # This multiply inherits from _FileIO and RawIOBase to make
616 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
617 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
618 # to do since _fileio.c is written in C).
Guido van Rossuma9e20242007-03-08 00:43:48 +0000619
Barry Warsaw40e82462008-11-20 20:14:50 +0000620 def __init__(self, name, mode="r", closefd=True):
621 _fileio._FileIO.__init__(self, name, mode, closefd)
622 self._name = name
623
Guido van Rossum87429772007-04-10 21:06:59 +0000624 def close(self):
625 _fileio._FileIO.close(self)
626 RawIOBase.close(self)
627
Guido van Rossum13633bb2007-04-13 18:42:35 +0000628 @property
629 def name(self):
630 return self._name
631
Guido van Rossuma9e20242007-03-08 00:43:48 +0000632
Guido van Rossumcce92b22007-04-10 14:41:39 +0000633class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000634
635 """Base class for buffered IO objects.
636
637 The main difference with RawIOBase is that the read() method
638 supports omitting the size argument, and does not have a default
639 implementation that defers to readinto().
640
641 In addition, read(), readinto() and write() may raise
642 BlockingIOError if the underlying raw stream is in non-blocking
643 mode and not ready; unlike their raw counterparts, they will never
644 return None.
645
646 A typical implementation should not inherit from a RawIOBase
647 implementation, but wrap one.
648 """
649
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000650 def read(self, n: int = None) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000651 """Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000652
Guido van Rossum024da5c2007-05-17 23:59:11 +0000653 If the argument is omitted, None, or negative, reads and
654 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000655
656 If the argument is positive, and the underlying raw stream is
657 not 'interactive', multiple raw reads may be issued to satisfy
658 the byte count (unless EOF is reached first). But for
659 interactive raw streams (XXX and for pipes?), at most one raw
660 read will be issued, and a short result does not imply that
661 EOF is imminent.
662
663 Returns an empty bytes array on EOF.
664
665 Raises BlockingIOError if the underlying raw stream has no
666 data at the moment.
667 """
668 self._unsupported("read")
669
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000670 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000671 """Read up to len(b) bytes into b.
Guido van Rossum141f7672007-04-10 00:22:16 +0000672
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000673 Like read(), this may issue multiple reads to the underlying raw
674 stream, unless the latter is 'interactive'.
Guido van Rossum141f7672007-04-10 00:22:16 +0000675
676 Returns the number of bytes read (0 for EOF).
677
678 Raises BlockingIOError if the underlying raw stream has no
679 data at the moment.
680 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000681 # XXX This ought to work with anything that supports the buffer API
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000682 self._checkClosed()
Guido van Rossum87429772007-04-10 21:06:59 +0000683 data = self.read(len(b))
684 n = len(data)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000685 try:
686 b[:n] = data
687 except TypeError as err:
688 import array
689 if not isinstance(b, array.array):
690 raise err
691 b[:n] = array.array('b', data)
Guido van Rossum87429772007-04-10 21:06:59 +0000692 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000693
694 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000695 """Write the given buffer to the IO stream.
Guido van Rossum141f7672007-04-10 00:22:16 +0000696
Christian Heimes5d8da202008-05-06 13:58:24 +0000697 Return the number of bytes written, which is never less than
Guido van Rossum141f7672007-04-10 00:22:16 +0000698 len(b).
699
700 Raises BlockingIOError if the buffer is full and the
701 underlying raw stream cannot accept more data at the moment.
702 """
703 self._unsupported("write")
704
705
706class _BufferedIOMixin(BufferedIOBase):
707
708 """A mixin implementation of BufferedIOBase with an underlying raw stream.
709
710 This passes most requests on to the underlying raw stream. It
711 does *not* provide implementations of read(), readinto() or
712 write().
713 """
714
715 def __init__(self, raw):
716 self.raw = raw
717
718 ### Positioning ###
719
720 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000721 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000722
723 def tell(self):
724 return self.raw.tell()
725
726 def truncate(self, pos=None):
Guido van Rossum79b79ee2007-10-25 23:21:03 +0000727 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
728 # and a flush may be necessary to synch both views of the current
729 # file state.
730 self.flush()
Guido van Rossum57233cb2007-10-26 17:19:33 +0000731
732 if pos is None:
733 pos = self.tell()
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000734 # XXX: Should seek() be used, instead of passing the position
735 # XXX directly to truncate?
Guido van Rossum57233cb2007-10-26 17:19:33 +0000736 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000737
738 ### Flush and close ###
739
740 def flush(self):
741 self.raw.flush()
742
743 def close(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000744 if not self.closed:
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000745 try:
746 self.flush()
747 except IOError:
748 pass # If flush() fails, just give up
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000749 self.raw.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000750
751 ### Inquiries ###
752
753 def seekable(self):
754 return self.raw.seekable()
755
756 def readable(self):
757 return self.raw.readable()
758
759 def writable(self):
760 return self.raw.writable()
761
762 @property
763 def closed(self):
764 return self.raw.closed
765
Barry Warsaw40e82462008-11-20 20:14:50 +0000766 @property
767 def name(self):
768 return self.raw.name
769
770 @property
771 def mode(self):
772 return self.raw.mode
773
Guido van Rossum141f7672007-04-10 00:22:16 +0000774 ### Lower-level APIs ###
775
776 def fileno(self):
777 return self.raw.fileno()
778
779 def isatty(self):
780 return self.raw.isatty()
781
782
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000783class _BytesIO(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000784
Guido van Rossum024da5c2007-05-17 23:59:11 +0000785 """Buffered I/O implementation using an in-memory bytes buffer."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000786
Guido van Rossum024da5c2007-05-17 23:59:11 +0000787 def __init__(self, initial_bytes=None):
Guido van Rossum254348e2007-11-21 19:29:53 +0000788 buf = bytearray()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000789 if initial_bytes is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000790 buf += initial_bytes
791 self._buffer = buf
Guido van Rossum28524c72007-02-27 05:47:44 +0000792 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000793
794 def getvalue(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000795 """Return the bytes value (contents) of the buffer
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000796 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000797 self._checkClosed()
Guido van Rossum98297ee2007-11-06 21:34:58 +0000798 return bytes(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000799
Guido van Rossum024da5c2007-05-17 23:59:11 +0000800 def read(self, n=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000801 self._checkClosed()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000802 if n is None:
803 n = -1
Guido van Rossum141f7672007-04-10 00:22:16 +0000804 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000805 n = len(self._buffer)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000806 if len(self._buffer) <= self._pos:
Alexandre Vassalotti2e0419d2008-05-07 00:09:04 +0000807 return b""
Guido van Rossum28524c72007-02-27 05:47:44 +0000808 newpos = min(len(self._buffer), self._pos + n)
809 b = self._buffer[self._pos : newpos]
810 self._pos = newpos
Guido van Rossum98297ee2007-11-06 21:34:58 +0000811 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000812
Guido van Rossum024da5c2007-05-17 23:59:11 +0000813 def read1(self, n):
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000814 """This is the same as read.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000815 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000816 return self.read(n)
817
Guido van Rossum28524c72007-02-27 05:47:44 +0000818 def write(self, b):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000819 self._checkClosed()
Guido van Rossuma74184e2007-08-29 04:05:57 +0000820 if isinstance(b, str):
821 raise TypeError("can't write str to binary stream")
Guido van Rossum28524c72007-02-27 05:47:44 +0000822 n = len(b)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000823 if n == 0:
824 return 0
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000825 pos = self._pos
826 if pos > len(self._buffer):
Guido van Rossumb972a782007-07-21 00:25:15 +0000827 # Inserts null bytes between the current end of the file
828 # and the new write position.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000829 padding = b'\x00' * (pos - len(self._buffer))
830 self._buffer += padding
831 self._buffer[pos:pos + n] = b
832 self._pos += n
Guido van Rossum28524c72007-02-27 05:47:44 +0000833 return n
834
835 def seek(self, pos, whence=0):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000836 self._checkClosed()
Christian Heimes3ab4f652007-11-09 01:27:29 +0000837 try:
838 pos = pos.__index__()
839 except AttributeError as err:
840 raise TypeError("an integer is required") from err
Guido van Rossum28524c72007-02-27 05:47:44 +0000841 if whence == 0:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000842 if pos < 0:
843 raise ValueError("negative seek position %r" % (pos,))
Alexandre Vassalottif0c0ff62008-05-09 21:21:21 +0000844 self._pos = pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000845 elif whence == 1:
846 self._pos = max(0, self._pos + pos)
847 elif whence == 2:
848 self._pos = max(0, len(self._buffer) + pos)
849 else:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000850 raise ValueError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000851 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000852
853 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000854 self._checkClosed()
Guido van Rossum28524c72007-02-27 05:47:44 +0000855 return self._pos
856
857 def truncate(self, pos=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000858 self._checkClosed()
Guido van Rossum28524c72007-02-27 05:47:44 +0000859 if pos is None:
860 pos = self._pos
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000861 elif pos < 0:
862 raise ValueError("negative truncate position %r" % (pos,))
Guido van Rossum28524c72007-02-27 05:47:44 +0000863 del self._buffer[pos:]
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000864 return self.seek(pos)
Guido van Rossum28524c72007-02-27 05:47:44 +0000865
866 def readable(self):
867 return True
868
869 def writable(self):
870 return True
871
872 def seekable(self):
873 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000874
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000875# Use the faster implementation of BytesIO if available
876try:
877 import _bytesio
878
879 class BytesIO(_bytesio._BytesIO, BufferedIOBase):
880 __doc__ = _bytesio._BytesIO.__doc__
881
882except ImportError:
883 BytesIO = _BytesIO
884
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000885
Guido van Rossum141f7672007-04-10 00:22:16 +0000886class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000887
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000888 """BufferedReader(raw[, buffer_size])
889
890 A buffer for a readable, sequential BaseRawIO object.
891
892 The constructor creates a BufferedReader for the given readable raw
893 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
894 is used.
895 """
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000896
Guido van Rossum78892e42007-04-06 17:31:18 +0000897 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000898 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000899 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000900 raw._checkReadable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000901 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum78892e42007-04-06 17:31:18 +0000902 self.buffer_size = buffer_size
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000903 self._reset_read_buf()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +0000904 self._read_lock = Lock()
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000905
906 def _reset_read_buf(self):
907 self._read_buf = b""
908 self._read_pos = 0
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000909
Guido van Rossum024da5c2007-05-17 23:59:11 +0000910 def read(self, n=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000911 """Read n bytes.
912
913 Returns exactly n bytes of data unless the underlying raw IO
Walter Dörwalda3270002007-05-29 19:13:29 +0000914 stream reaches EOF or if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000915 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000916 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000917 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000918 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +0000919 with self._read_lock:
920 return self._read_unlocked(n)
921
922 def _read_unlocked(self, n=None):
Guido van Rossum78892e42007-04-06 17:31:18 +0000923 nodata_val = b""
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000924 empty_values = (b"", None)
925 buf = self._read_buf
926 pos = self._read_pos
927
928 # Special case for when the number of bytes to read is unspecified.
929 if n is None or n == -1:
930 self._reset_read_buf()
931 chunks = [buf[pos:]] # Strip the consumed bytes.
932 current_size = 0
933 while True:
934 # Read until EOF or until read() would block.
935 chunk = self.raw.read()
936 if chunk in empty_values:
937 nodata_val = chunk
938 break
939 current_size += len(chunk)
940 chunks.append(chunk)
941 return b"".join(chunks) or nodata_val
942
943 # The number of bytes to read is specified, return at most n bytes.
944 avail = len(buf) - pos # Length of the available buffered data.
945 if n <= avail:
946 # Fast path: the data to read is fully buffered.
947 self._read_pos += n
948 return buf[pos:pos+n]
949 # Slow path: read from the stream until enough bytes are read,
950 # or until an EOF occurs or until read() would block.
951 chunks = [buf[pos:]]
952 wanted = max(self.buffer_size, n)
953 while avail < n:
954 chunk = self.raw.read(wanted)
955 if chunk in empty_values:
956 nodata_val = chunk
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000957 break
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000958 avail += len(chunk)
959 chunks.append(chunk)
960 # n is more then avail only when an EOF occurred or when
961 # read() would have blocked.
962 n = min(n, avail)
963 out = b"".join(chunks)
964 self._read_buf = out[n:] # Save the extra data in the buffer.
965 self._read_pos = 0
966 return out[:n] if out else nodata_val
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000967
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000968 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000969 """Returns buffered bytes without advancing the position.
970
971 The argument indicates a desired minimal number of bytes; we
972 do at most one raw read to satisfy it. We never return more
973 than self.buffer_size.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000974 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000975 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +0000976 with self._read_lock:
977 return self._peek_unlocked(n)
978
979 def _peek_unlocked(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000980 want = min(n, self.buffer_size)
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000981 have = len(self._read_buf) - self._read_pos
Guido van Rossum13633bb2007-04-13 18:42:35 +0000982 if have < want:
983 to_read = self.buffer_size - have
984 current = self.raw.read(to_read)
985 if current:
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000986 self._read_buf = self._read_buf[self._read_pos:] + current
987 self._read_pos = 0
988 return self._read_buf[self._read_pos:]
Guido van Rossum13633bb2007-04-13 18:42:35 +0000989
990 def read1(self, n):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000991 """Reads up to n bytes, with at most one read() system call."""
992 # Returns up to n bytes. If at least one byte is buffered, we
993 # only return buffered bytes. Otherwise, we do one raw read.
Antoine Pitrou8043cf82009-01-09 19:54:29 +0000994 self._checkClosed()
Guido van Rossum13633bb2007-04-13 18:42:35 +0000995 if n <= 0:
996 return b""
Antoine Pitrou87695762008-08-14 22:44:29 +0000997 with self._read_lock:
998 self._peek_unlocked(1)
999 return self._read_unlocked(
1000 min(n, len(self._read_buf) - self._read_pos))
Guido van Rossum13633bb2007-04-13 18:42:35 +00001001
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001002 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001003 self._checkClosed()
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001004 return self.raw.tell() - len(self._read_buf) + self._read_pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001005
1006 def seek(self, pos, whence=0):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001007 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +00001008 with self._read_lock:
1009 if whence == 1:
1010 pos -= len(self._read_buf) - self._read_pos
1011 pos = self.raw.seek(pos, whence)
1012 self._reset_read_buf()
1013 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001014
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001015
Guido van Rossum141f7672007-04-10 00:22:16 +00001016class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001017
Christian Heimes5d8da202008-05-06 13:58:24 +00001018 """A buffer for a writeable sequential RawIO object.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001019
1020 The constructor creates a BufferedWriter for the given writeable raw
1021 stream. If the buffer_size is not given, it defaults to
1022 DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
1023 twice the buffer size.
1024 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001025
Guido van Rossum141f7672007-04-10 00:22:16 +00001026 def __init__(self, raw,
1027 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001028 raw._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001029 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001030 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +00001031 self.max_buffer_size = (2*buffer_size
1032 if max_buffer_size is None
1033 else max_buffer_size)
Guido van Rossum254348e2007-11-21 19:29:53 +00001034 self._write_buf = bytearray()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +00001035 self._write_lock = Lock()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001036
1037 def write(self, b):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001038 self._checkClosed()
Guido van Rossuma74184e2007-08-29 04:05:57 +00001039 if isinstance(b, str):
1040 raise TypeError("can't write str to binary stream")
Antoine Pitrou87695762008-08-14 22:44:29 +00001041 with self._write_lock:
1042 # XXX we can implement some more tricks to try and avoid
1043 # partial writes
1044 if len(self._write_buf) > self.buffer_size:
1045 # We're full, so let's pre-flush the buffer
1046 try:
1047 self._flush_unlocked()
1048 except BlockingIOError as e:
1049 # We can't accept anything else.
1050 # XXX Why not just let the exception pass through?
1051 raise BlockingIOError(e.errno, e.strerror, 0)
1052 before = len(self._write_buf)
1053 self._write_buf.extend(b)
1054 written = len(self._write_buf) - before
1055 if len(self._write_buf) > self.buffer_size:
1056 try:
1057 self._flush_unlocked()
1058 except BlockingIOError as e:
1059 if len(self._write_buf) > self.max_buffer_size:
1060 # We've hit max_buffer_size. We have to accept a
1061 # partial write and cut back our buffer.
1062 overage = len(self._write_buf) - self.max_buffer_size
1063 self._write_buf = self._write_buf[:self.max_buffer_size]
1064 raise BlockingIOError(e.errno, e.strerror, overage)
1065 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001066
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001067 def truncate(self, pos=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001068 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +00001069 with self._write_lock:
1070 self._flush_unlocked()
1071 if pos is None:
1072 pos = self.raw.tell()
1073 return self.raw.truncate(pos)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001074
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001075 def flush(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001076 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +00001077 with self._write_lock:
1078 self._flush_unlocked()
1079
1080 def _flush_unlocked(self):
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001081 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +00001082 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001083 while self._write_buf:
1084 n = self.raw.write(self._write_buf)
1085 del self._write_buf[:n]
1086 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001087 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001088 n = e.characters_written
1089 del self._write_buf[:n]
1090 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001091 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001092
1093 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001094 self._checkClosed()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001095 return self.raw.tell() + len(self._write_buf)
1096
1097 def seek(self, pos, whence=0):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001098 self._checkClosed()
Antoine Pitrou87695762008-08-14 22:44:29 +00001099 with self._write_lock:
1100 self._flush_unlocked()
1101 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001102
Guido van Rossum01a27522007-03-07 01:00:12 +00001103
Guido van Rossum141f7672007-04-10 00:22:16 +00001104class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001105
Guido van Rossum01a27522007-03-07 01:00:12 +00001106 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001107
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001108 A buffered reader object and buffered writer object put together to
1109 form a sequential IO object that can read and write. This is typically
1110 used with a socket or two-way pipe.
Guido van Rossum78892e42007-04-06 17:31:18 +00001111
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001112 reader and writer are RawIOBase objects that are readable and
1113 writeable respectively. If the buffer_size is omitted it defaults to
1114 DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
1115 defaults to twice the buffer size.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001116 """
1117
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001118 # XXX The usefulness of this (compared to having two separate IO
1119 # objects) is questionable.
1120
Guido van Rossum141f7672007-04-10 00:22:16 +00001121 def __init__(self, reader, writer,
1122 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1123 """Constructor.
1124
1125 The arguments are two RawIO instances.
1126 """
Guido van Rossum5abbf752007-08-27 17:39:33 +00001127 reader._checkReadable()
1128 writer._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001129 self.reader = BufferedReader(reader, buffer_size)
1130 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001131
Guido van Rossum024da5c2007-05-17 23:59:11 +00001132 def read(self, n=None):
1133 if n is None:
1134 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001135 return self.reader.read(n)
1136
Guido van Rossum141f7672007-04-10 00:22:16 +00001137 def readinto(self, b):
1138 return self.reader.readinto(b)
1139
Guido van Rossum01a27522007-03-07 01:00:12 +00001140 def write(self, b):
1141 return self.writer.write(b)
1142
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001143 def peek(self, n=0):
1144 return self.reader.peek(n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001145
1146 def read1(self, n):
1147 return self.reader.read1(n)
1148
Guido van Rossum01a27522007-03-07 01:00:12 +00001149 def readable(self):
1150 return self.reader.readable()
1151
1152 def writable(self):
1153 return self.writer.writable()
1154
1155 def flush(self):
1156 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001157
Guido van Rossum01a27522007-03-07 01:00:12 +00001158 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +00001159 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +00001160 self.reader.close()
1161
1162 def isatty(self):
1163 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +00001164
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001165 @property
1166 def closed(self):
Benjamin Peterson92035012008-12-27 16:00:54 +00001167 return self.writer.closed
Guido van Rossum01a27522007-03-07 01:00:12 +00001168
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001169
Guido van Rossum141f7672007-04-10 00:22:16 +00001170class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +00001171
Christian Heimes5d8da202008-05-06 13:58:24 +00001172 """A buffered interface to random access streams.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001173
1174 The constructor creates a reader and writer for a seekable stream,
1175 raw, given in the first argument. If the buffer_size is omitted it
1176 defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
1177 writer) defaults to twice the buffer size.
1178 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001179
Guido van Rossum141f7672007-04-10 00:22:16 +00001180 def __init__(self, raw,
1181 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001182 raw._checkSeekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001183 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001184 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1185
Guido van Rossum01a27522007-03-07 01:00:12 +00001186 def seek(self, pos, whence=0):
1187 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001188 # First do the raw seek, then empty the read buffer, so that
1189 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +00001190 pos = self.raw.seek(pos, whence)
Antoine Pitrou87695762008-08-14 22:44:29 +00001191 with self._read_lock:
1192 self._reset_read_buf()
Guido van Rossum53807da2007-04-10 19:01:47 +00001193 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +00001194
1195 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001196 self._checkClosed()
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001197 if self._write_buf:
Guido van Rossum01a27522007-03-07 01:00:12 +00001198 return self.raw.tell() + len(self._write_buf)
1199 else:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001200 return BufferedReader.tell(self)
Guido van Rossum01a27522007-03-07 01:00:12 +00001201
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001202 def truncate(self, pos=None):
1203 if pos is None:
1204 pos = self.tell()
1205 # Use seek to flush the read buffer.
1206 self.seek(pos)
1207 return BufferedWriter.truncate(self)
1208
Guido van Rossum024da5c2007-05-17 23:59:11 +00001209 def read(self, n=None):
1210 if n is None:
1211 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001212 self.flush()
1213 return BufferedReader.read(self, n)
1214
Guido van Rossum141f7672007-04-10 00:22:16 +00001215 def readinto(self, b):
1216 self.flush()
1217 return BufferedReader.readinto(self, b)
1218
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001219 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +00001220 self.flush()
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001221 return BufferedReader.peek(self, n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001222
1223 def read1(self, n):
1224 self.flush()
1225 return BufferedReader.read1(self, n)
1226
Guido van Rossum01a27522007-03-07 01:00:12 +00001227 def write(self, b):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001228 self._checkClosed()
Guido van Rossum78892e42007-04-06 17:31:18 +00001229 if self._read_buf:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001230 # Undo readahead
Antoine Pitrou87695762008-08-14 22:44:29 +00001231 with self._read_lock:
1232 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1233 self._reset_read_buf()
Guido van Rossum01a27522007-03-07 01:00:12 +00001234 return BufferedWriter.write(self, b)
1235
Guido van Rossum78892e42007-04-06 17:31:18 +00001236
Guido van Rossumcce92b22007-04-10 14:41:39 +00001237class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +00001238
1239 """Base class for text I/O.
1240
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001241 This class provides a character and line based interface to stream
1242 I/O. There is no readinto method because Python's character strings
1243 are immutable. There is no public constructor.
Guido van Rossum78892e42007-04-06 17:31:18 +00001244 """
1245
1246 def read(self, n: int = -1) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001247 """Read at most n characters from stream.
Guido van Rossum78892e42007-04-06 17:31:18 +00001248
1249 Read from underlying buffer until we have n characters or we hit EOF.
1250 If n is negative or omitted, read until EOF.
1251 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001252 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +00001253
Guido van Rossum9b76da62007-04-11 01:09:03 +00001254 def write(self, s: str) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001255 """Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001256 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +00001257
Guido van Rossum9b76da62007-04-11 01:09:03 +00001258 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001259 """Truncate size to pos."""
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001260 self._unsupported("truncate")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001261
Guido van Rossum78892e42007-04-06 17:31:18 +00001262 def readline(self) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001263 """Read until newline or EOF.
Guido van Rossum78892e42007-04-06 17:31:18 +00001264
1265 Returns an empty string if EOF is hit immediately.
1266 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001267 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +00001268
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001269 @property
1270 def encoding(self):
1271 """Subclasses should override."""
1272 return None
1273
Guido van Rossum8358db22007-08-18 21:39:55 +00001274 @property
1275 def newlines(self):
Christian Heimes5d8da202008-05-06 13:58:24 +00001276 """Line endings translated so far.
Guido van Rossum8358db22007-08-18 21:39:55 +00001277
1278 Only line endings translated during reading are considered.
1279
1280 Subclasses should override.
1281 """
1282 return None
1283
Guido van Rossum78892e42007-04-06 17:31:18 +00001284
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001285class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001286 r"""Codec used when reading a file in universal newlines mode. It wraps
1287 another incremental decoder, translating \r\n and \r into \n. It also
1288 records the types of newlines encountered. When used with
1289 translate=False, it ensures that the newline sequence is returned in
1290 one piece.
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001291 """
1292 def __init__(self, decoder, translate, errors='strict'):
1293 codecs.IncrementalDecoder.__init__(self, errors=errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001294 self.translate = translate
1295 self.decoder = decoder
1296 self.seennl = 0
Antoine Pitrou180a3362008-12-14 16:36:46 +00001297 self.pendingcr = False
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001298
1299 def decode(self, input, final=False):
1300 # decode input (with the eventual \r from a previous pass)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001301 output = self.decoder.decode(input, final=final)
Antoine Pitrou180a3362008-12-14 16:36:46 +00001302 if self.pendingcr and (output or final):
1303 output = "\r" + output
1304 self.pendingcr = False
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001305
1306 # retain last \r even when not translating data:
1307 # then readline() is sure to get \r\n in one pass
1308 if output.endswith("\r") and not final:
1309 output = output[:-1]
Antoine Pitrou180a3362008-12-14 16:36:46 +00001310 self.pendingcr = True
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001311
1312 # Record which newlines are read
1313 crlf = output.count('\r\n')
1314 cr = output.count('\r') - crlf
1315 lf = output.count('\n') - crlf
1316 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1317 | (crlf and self._CRLF)
1318
1319 if self.translate:
1320 if crlf:
1321 output = output.replace("\r\n", "\n")
1322 if cr:
1323 output = output.replace("\r", "\n")
1324
1325 return output
1326
1327 def getstate(self):
1328 buf, flag = self.decoder.getstate()
Antoine Pitrou180a3362008-12-14 16:36:46 +00001329 flag <<= 1
1330 if self.pendingcr:
1331 flag |= 1
1332 return buf, flag
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001333
1334 def setstate(self, state):
1335 buf, flag = state
Antoine Pitrou180a3362008-12-14 16:36:46 +00001336 self.pendingcr = bool(flag & 1)
1337 self.decoder.setstate((buf, flag >> 1))
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001338
1339 def reset(self):
Alexandre Vassalottic3d7fe02007-12-28 01:24:22 +00001340 self.seennl = 0
Antoine Pitrou180a3362008-12-14 16:36:46 +00001341 self.pendingcr = False
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001342 self.decoder.reset()
1343
1344 _LF = 1
1345 _CR = 2
1346 _CRLF = 4
1347
1348 @property
1349 def newlines(self):
1350 return (None,
1351 "\n",
1352 "\r",
1353 ("\r", "\n"),
1354 "\r\n",
1355 ("\n", "\r\n"),
1356 ("\r", "\r\n"),
1357 ("\r", "\n", "\r\n")
1358 )[self.seennl]
1359
1360
Guido van Rossum78892e42007-04-06 17:31:18 +00001361class TextIOWrapper(TextIOBase):
1362
Christian Heimes5d8da202008-05-06 13:58:24 +00001363 r"""Character and line based layer over a BufferedIOBase object, buffer.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001364
1365 encoding gives the name of the encoding that the stream will be
1366 decoded or encoded with. It defaults to locale.getpreferredencoding.
1367
1368 errors determines the strictness of encoding and decoding (see the
1369 codecs.register) and defaults to "strict".
1370
1371 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1372 handling of line endings. If it is None, universal newlines is
1373 enabled. With this enabled, on input, the lines endings '\n', '\r',
1374 or '\r\n' are translated to '\n' before being returned to the
1375 caller. Conversely, on output, '\n' is translated to the system
1376 default line seperator, os.linesep. If newline is any other of its
1377 legal values, that newline becomes the newline when the file is read
1378 and it is returned untranslated. On output, '\n' is converted to the
1379 newline.
1380
1381 If line_buffering is True, a call to flush is implied when a call to
1382 write contains a newline character.
Guido van Rossum78892e42007-04-06 17:31:18 +00001383 """
1384
Antoine Pitrou56b3a402008-12-15 23:01:43 +00001385 _CHUNK_SIZE = 2048
Guido van Rossum78892e42007-04-06 17:31:18 +00001386
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001387 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1388 line_buffering=False):
Guido van Rossum8358db22007-08-18 21:39:55 +00001389 if newline not in (None, "", "\n", "\r", "\r\n"):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001390 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +00001391 if encoding is None:
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001392 try:
1393 encoding = os.device_encoding(buffer.fileno())
Brett Cannon041683d2007-10-11 23:08:53 +00001394 except (AttributeError, UnsupportedOperation):
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001395 pass
1396 if encoding is None:
Martin v. Löwisd78d3b42007-08-11 15:36:45 +00001397 try:
1398 import locale
1399 except ImportError:
1400 # Importing locale may fail if Python is being built
1401 encoding = "ascii"
1402 else:
1403 encoding = locale.getpreferredencoding()
Guido van Rossum78892e42007-04-06 17:31:18 +00001404
Christian Heimes8bd14fb2007-11-08 16:34:32 +00001405 if not isinstance(encoding, str):
1406 raise ValueError("invalid encoding: %r" % encoding)
1407
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001408 if errors is None:
1409 errors = "strict"
1410 else:
1411 if not isinstance(errors, str):
1412 raise ValueError("invalid errors: %r" % errors)
1413
Guido van Rossum78892e42007-04-06 17:31:18 +00001414 self.buffer = buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001415 self._line_buffering = line_buffering
Guido van Rossum78892e42007-04-06 17:31:18 +00001416 self._encoding = encoding
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001417 self._errors = errors
Guido van Rossum8358db22007-08-18 21:39:55 +00001418 self._readuniversal = not newline
1419 self._readtranslate = newline is None
1420 self._readnl = newline
1421 self._writetranslate = newline != ''
1422 self._writenl = newline or os.linesep
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001423 self._encoder = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001424 self._decoder = None
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001425 self._decoded_chars = '' # buffer for text returned from decoder
1426 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001427 self._snapshot = None # info for reconstructing decoder state
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001428 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001429
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001430 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1431 # where dec_flags is the second (integer) item of the decoder state
1432 # and next_input is the chunk of input bytes that comes next after the
1433 # snapshot point. We use this to reconstruct decoder states in tell().
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001434
1435 # Naming convention:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001436 # - "bytes_..." for integer variables that count input bytes
1437 # - "chars_..." for integer variables that count decoded characters
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001438
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001439 @property
1440 def encoding(self):
1441 return self._encoding
1442
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001443 @property
1444 def errors(self):
1445 return self._errors
1446
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001447 @property
1448 def line_buffering(self):
1449 return self._line_buffering
1450
Ka-Ping Yeeddaa7062008-03-17 20:35:15 +00001451 def seekable(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001452 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +00001453
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001454 def readable(self):
1455 return self.buffer.readable()
1456
1457 def writable(self):
1458 return self.buffer.writable()
1459
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001460 def flush(self):
1461 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001462 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001463
1464 def close(self):
Guido van Rossum33e7a8e2007-07-22 20:38:07 +00001465 try:
1466 self.flush()
1467 except:
1468 pass # If flush() fails, just give up
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001469 self.buffer.close()
1470
1471 @property
1472 def closed(self):
1473 return self.buffer.closed
1474
Barry Warsaw40e82462008-11-20 20:14:50 +00001475 @property
1476 def name(self):
1477 return self.buffer.name
1478
Guido van Rossum9be55972007-04-07 02:59:27 +00001479 def fileno(self):
1480 return self.buffer.fileno()
1481
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001482 def isatty(self):
1483 return self.buffer.isatty()
1484
Guido van Rossum78892e42007-04-06 17:31:18 +00001485 def write(self, s: str):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001486 self._checkClosed()
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001487 if not isinstance(s, str):
Guido van Rossumdcce8392007-08-29 18:10:08 +00001488 raise TypeError("can't write %s to text stream" %
1489 s.__class__.__name__)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001490 length = len(s)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001491 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
Guido van Rossum8358db22007-08-18 21:39:55 +00001492 if haslf and self._writetranslate and self._writenl != "\n":
1493 s = s.replace("\n", self._writenl)
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001494 encoder = self._encoder or self._get_encoder()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001495 # XXX What if we were just reading?
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001496 b = encoder.encode(s)
Guido van Rossum8358db22007-08-18 21:39:55 +00001497 self.buffer.write(b)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001498 if self._line_buffering and (haslf or "\r" in s):
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001499 self.flush()
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001500 self._snapshot = None
1501 if self._decoder:
1502 self._decoder.reset()
1503 return length
Guido van Rossum78892e42007-04-06 17:31:18 +00001504
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001505 def _get_encoder(self):
1506 make_encoder = codecs.getincrementalencoder(self._encoding)
1507 self._encoder = make_encoder(self._errors)
1508 return self._encoder
1509
Guido van Rossum78892e42007-04-06 17:31:18 +00001510 def _get_decoder(self):
1511 make_decoder = codecs.getincrementaldecoder(self._encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001512 decoder = make_decoder(self._errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001513 if self._readuniversal:
1514 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1515 self._decoder = decoder
Guido van Rossum78892e42007-04-06 17:31:18 +00001516 return decoder
1517
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001518 # The following three methods implement an ADT for _decoded_chars.
1519 # Text returned from the decoder is buffered here until the client
1520 # requests it by calling our read() or readline() method.
1521 def _set_decoded_chars(self, chars):
1522 """Set the _decoded_chars buffer."""
1523 self._decoded_chars = chars
1524 self._decoded_chars_used = 0
1525
1526 def _get_decoded_chars(self, n=None):
1527 """Advance into the _decoded_chars buffer."""
1528 offset = self._decoded_chars_used
1529 if n is None:
1530 chars = self._decoded_chars[offset:]
1531 else:
1532 chars = self._decoded_chars[offset:offset + n]
1533 self._decoded_chars_used += len(chars)
1534 return chars
1535
1536 def _rewind_decoded_chars(self, n):
1537 """Rewind the _decoded_chars buffer."""
1538 if self._decoded_chars_used < n:
1539 raise AssertionError("rewind decoded_chars out of bounds")
1540 self._decoded_chars_used -= n
1541
Guido van Rossum9b76da62007-04-11 01:09:03 +00001542 def _read_chunk(self):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001543 """
1544 Read and decode the next chunk of data from the BufferedReader.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001545 """
1546
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001547 # The return value is True unless EOF was reached. The decoded
1548 # string is placed in self._decoded_chars (replacing its previous
1549 # value). The entire input chunk is sent to the decoder, though
1550 # some of it may remain buffered in the decoder, yet to be
1551 # converted.
1552
Guido van Rossum5abbf752007-08-27 17:39:33 +00001553 if self._decoder is None:
1554 raise ValueError("no decoder")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001555
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001556 if self._telling:
1557 # To prepare for tell(), we need to snapshot a point in the
1558 # file where the decoder's input buffer is empty.
Guido van Rossum9b76da62007-04-11 01:09:03 +00001559
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001560 dec_buffer, dec_flags = self._decoder.getstate()
1561 # Given this, we know there was a valid snapshot point
1562 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001563
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001564 # Read a chunk, decode it, and put the result in self._decoded_chars.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001565 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1566 eof = not input_chunk
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001567 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001568
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001569 if self._telling:
1570 # At the snapshot point, len(dec_buffer) bytes before the read,
1571 # the next input to be decoded is dec_buffer + input_chunk.
1572 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1573
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001574 return not eof
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001575
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001576 def _pack_cookie(self, position, dec_flags=0,
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001577 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001578 # The meaning of a tell() cookie is: seek to position, set the
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001579 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001580 # into the decoder with need_eof as the EOF flag, then skip
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001581 # chars_to_skip characters of the decoded result. For most simple
1582 # decoders, tell() will often just give a byte offset in the file.
1583 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1584 (chars_to_skip<<192) | bool(need_eof)<<256)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001585
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001586 def _unpack_cookie(self, bigint):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001587 rest, position = divmod(bigint, 1<<64)
1588 rest, dec_flags = divmod(rest, 1<<64)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001589 rest, bytes_to_feed = divmod(rest, 1<<64)
1590 need_eof, chars_to_skip = divmod(rest, 1<<64)
1591 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
Guido van Rossum9b76da62007-04-11 01:09:03 +00001592
1593 def tell(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001594 self._checkClosed()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001595 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001596 raise IOError("underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001597 if not self._telling:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001598 raise IOError("telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001599 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001600 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001601 decoder = self._decoder
1602 if decoder is None or self._snapshot is None:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001603 if self._decoded_chars:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001604 # This should never happen.
1605 raise AssertionError("pending decoded text")
Guido van Rossumcba608c2007-04-11 14:19:59 +00001606 return position
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001607
1608 # Skip backward to the snapshot point (see _read_chunk).
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001609 dec_flags, next_input = self._snapshot
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001610 position -= len(next_input)
1611
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001612 # How many decoded characters have been used up since the snapshot?
1613 chars_to_skip = self._decoded_chars_used
1614 if chars_to_skip == 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001615 # We haven't moved from the snapshot point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001616 return self._pack_cookie(position, dec_flags)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001617
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001618 # Starting from the snapshot position, we will walk the decoder
1619 # forward until it gives us enough decoded characters.
Guido van Rossumd76e7792007-04-17 02:38:04 +00001620 saved_state = decoder.getstate()
1621 try:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001622 # Note our initial start point.
1623 decoder.setstate((b'', dec_flags))
1624 start_pos = position
1625 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001626 need_eof = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001627
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001628 # Feed the decoder one byte at a time. As we go, note the
1629 # nearest "safe start point" before the current location
1630 # (a point where the decoder has nothing buffered, so seek()
1631 # can safely start from there and advance to this location).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001632 next_byte = bytearray(1)
1633 for next_byte[0] in next_input:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001634 bytes_fed += 1
1635 chars_decoded += len(decoder.decode(next_byte))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001636 dec_buffer, dec_flags = decoder.getstate()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001637 if not dec_buffer and chars_decoded <= chars_to_skip:
1638 # Decoder buffer is empty, so this is a safe start point.
1639 start_pos += bytes_fed
1640 chars_to_skip -= chars_decoded
1641 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1642 if chars_decoded >= chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001643 break
1644 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001645 # We didn't get enough decoded data; signal EOF to get more.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001646 chars_decoded += len(decoder.decode(b'', final=True))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001647 need_eof = 1
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001648 if chars_decoded < chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001649 raise IOError("can't reconstruct logical file position")
1650
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001651 # The returned cookie corresponds to the last safe start point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001652 return self._pack_cookie(
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001653 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001654 finally:
1655 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001656
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001657 def truncate(self, pos=None):
1658 self.flush()
1659 if pos is None:
1660 pos = self.tell()
1661 self.seek(pos)
1662 return self.buffer.truncate()
1663
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001664 def seek(self, cookie, whence=0):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001665 self._checkClosed()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001666 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001667 raise IOError("underlying stream is not seekable")
1668 if whence == 1: # seek relative to current position
1669 if cookie != 0:
1670 raise IOError("can't do nonzero cur-relative seeks")
1671 # Seeking to the current position should attempt to
1672 # sync the underlying buffer with the current position.
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001673 whence = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001674 cookie = self.tell()
1675 if whence == 2: # seek relative to end of file
1676 if cookie != 0:
1677 raise IOError("can't do nonzero end-relative seeks")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001678 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001679 position = self.buffer.seek(0, 2)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001680 self._set_decoded_chars('')
1681 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001682 if self._decoder:
1683 self._decoder.reset()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001684 return position
Guido van Rossum9b76da62007-04-11 01:09:03 +00001685 if whence != 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001686 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
Guido van Rossum9b76da62007-04-11 01:09:03 +00001687 (whence,))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001688 if cookie < 0:
1689 raise ValueError("negative seek position %r" % (cookie,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001690 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001691
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001692 # The strategy of seek() is to go back to the safe start point
1693 # and replay the effect of read(chars_to_skip) from there.
1694 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001695 self._unpack_cookie(cookie)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001696
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001697 # Seek back to the safe start point.
1698 self.buffer.seek(start_pos)
1699 self._set_decoded_chars('')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001700 self._snapshot = None
1701
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001702 # Restore the decoder to its state from the safe start point.
1703 if self._decoder or dec_flags or chars_to_skip:
1704 self._decoder = self._decoder or self._get_decoder()
1705 self._decoder.setstate((b'', dec_flags))
1706 self._snapshot = (dec_flags, b'')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001707
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001708 if chars_to_skip:
1709 # Just like _read_chunk, feed the decoder and save a snapshot.
1710 input_chunk = self.buffer.read(bytes_to_feed)
1711 self._set_decoded_chars(
1712 self._decoder.decode(input_chunk, need_eof))
1713 self._snapshot = (dec_flags, input_chunk)
1714
1715 # Skip chars_to_skip of the decoded characters.
1716 if len(self._decoded_chars) < chars_to_skip:
1717 raise IOError("can't restore logical file position")
1718 self._decoded_chars_used = chars_to_skip
1719
1720 return cookie
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001721
Guido van Rossum024da5c2007-05-17 23:59:11 +00001722 def read(self, n=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001723 self._checkClosed()
Guido van Rossum024da5c2007-05-17 23:59:11 +00001724 if n is None:
1725 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001726 decoder = self._decoder or self._get_decoder()
Guido van Rossum78892e42007-04-06 17:31:18 +00001727 if n < 0:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001728 # Read everything.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001729 result = (self._get_decoded_chars() +
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001730 decoder.decode(self.buffer.read(), final=True))
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001731 self._set_decoded_chars('')
1732 self._snapshot = None
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001733 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001734 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001735 # Keep reading chunks until we have n characters to return.
1736 eof = False
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001737 result = self._get_decoded_chars(n)
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001738 while len(result) < n and not eof:
1739 eof = not self._read_chunk()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001740 result += self._get_decoded_chars(n - len(result))
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001741 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001742
Guido van Rossum024da5c2007-05-17 23:59:11 +00001743 def __next__(self):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001744 self._checkClosed()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001745 self._telling = False
1746 line = self.readline()
1747 if not line:
1748 self._snapshot = None
1749 self._telling = self._seekable
1750 raise StopIteration
1751 return line
1752
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001753 def readline(self, limit=None):
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001754 self._checkClosed()
Guido van Rossum98297ee2007-11-06 21:34:58 +00001755 if limit is None:
1756 limit = -1
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001757
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001758 # Grab all the decoded text (we will rewind any extra bits later).
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001759 line = self._get_decoded_chars()
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001760
Guido van Rossum78892e42007-04-06 17:31:18 +00001761 start = 0
1762 decoder = self._decoder or self._get_decoder()
1763
Guido van Rossum8358db22007-08-18 21:39:55 +00001764 pos = endpos = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001765 while True:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001766 if self._readtranslate:
1767 # Newlines are already translated, only search for \n
1768 pos = line.find('\n', start)
1769 if pos >= 0:
1770 endpos = pos + 1
1771 break
1772 else:
1773 start = len(line)
1774
1775 elif self._readuniversal:
Guido van Rossum8358db22007-08-18 21:39:55 +00001776 # Universal newline search. Find any of \r, \r\n, \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001777 # The decoder ensures that \r\n are not split in two pieces
Guido van Rossum78892e42007-04-06 17:31:18 +00001778
Guido van Rossum8358db22007-08-18 21:39:55 +00001779 # In C we'd look for these in parallel of course.
1780 nlpos = line.find("\n", start)
1781 crpos = line.find("\r", start)
1782 if crpos == -1:
1783 if nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001784 # Nothing found
Guido van Rossum8358db22007-08-18 21:39:55 +00001785 start = len(line)
Guido van Rossum78892e42007-04-06 17:31:18 +00001786 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001787 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001788 endpos = nlpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001789 break
1790 elif nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001791 # Found lone \r
1792 endpos = crpos + 1
1793 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001794 elif nlpos < crpos:
1795 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001796 endpos = nlpos + 1
Guido van Rossum78892e42007-04-06 17:31:18 +00001797 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001798 elif nlpos == crpos + 1:
1799 # Found \r\n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001800 endpos = crpos + 2
Guido van Rossum8358db22007-08-18 21:39:55 +00001801 break
1802 else:
1803 # Found \r
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001804 endpos = crpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001805 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001806 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001807 # non-universal
1808 pos = line.find(self._readnl)
1809 if pos >= 0:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001810 endpos = pos + len(self._readnl)
Guido van Rossum8358db22007-08-18 21:39:55 +00001811 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001812
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001813 if limit >= 0 and len(line) >= limit:
1814 endpos = limit # reached length limit
1815 break
1816
Guido van Rossum78892e42007-04-06 17:31:18 +00001817 # No line ending seen yet - get more data
Guido van Rossum8358db22007-08-18 21:39:55 +00001818 more_line = ''
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001819 while self._read_chunk():
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001820 if self._decoded_chars:
Guido van Rossum78892e42007-04-06 17:31:18 +00001821 break
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001822 if self._decoded_chars:
1823 line += self._get_decoded_chars()
Guido van Rossum8358db22007-08-18 21:39:55 +00001824 else:
1825 # end of file
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001826 self._set_decoded_chars('')
1827 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001828 return line
Guido van Rossum78892e42007-04-06 17:31:18 +00001829
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001830 if limit >= 0 and endpos > limit:
1831 endpos = limit # don't exceed limit
1832
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001833 # Rewind _decoded_chars to just after the line ending we found.
1834 self._rewind_decoded_chars(len(line) - endpos)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001835 return line[:endpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001836
Guido van Rossum8358db22007-08-18 21:39:55 +00001837 @property
1838 def newlines(self):
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001839 return self._decoder.newlines if self._decoder else None
Guido van Rossum024da5c2007-05-17 23:59:11 +00001840
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001841class _StringIO(TextIOWrapper):
1842 """Text I/O implementation using an in-memory buffer.
1843
1844 The initial_value argument sets the value of object. The newline
1845 argument is like the one of TextIOWrapper's constructor.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001846 """
Guido van Rossum024da5c2007-05-17 23:59:11 +00001847
1848 # XXX This is really slow, but fully functional
1849
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001850 def __init__(self, initial_value="", newline="\n"):
1851 super(_StringIO, self).__init__(BytesIO(),
1852 encoding="utf-8",
1853 errors="strict",
1854 newline=newline)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001855 if initial_value:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001856 if not isinstance(initial_value, str):
Guido van Rossum34d19282007-08-09 01:03:29 +00001857 initial_value = str(initial_value)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001858 self.write(initial_value)
1859 self.seek(0)
1860
1861 def getvalue(self):
Guido van Rossum34d19282007-08-09 01:03:29 +00001862 self.flush()
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001863 return self.buffer.getvalue().decode(self._encoding, self._errors)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001864
1865try:
1866 import _stringio
1867
1868 # This subclass is a reimplementation of the TextIOWrapper
1869 # interface without any of its text decoding facilities. All the
1870 # stored data is manipulated with the efficient
1871 # _stringio._StringIO extension type. Also, the newline decoding
1872 # mechanism of IncrementalNewlineDecoder is reimplemented here for
1873 # efficiency. Doing otherwise, would require us to implement a
1874 # fake decoder which would add an additional and unnecessary layer
1875 # on top of the _StringIO methods.
1876
1877 class StringIO(_stringio._StringIO, TextIOBase):
1878 """Text I/O implementation using an in-memory buffer.
1879
1880 The initial_value argument sets the value of object. The newline
1881 argument is like the one of TextIOWrapper's constructor.
1882 """
1883
1884 _CHUNK_SIZE = 4096
1885
1886 def __init__(self, initial_value="", newline="\n"):
1887 if newline not in (None, "", "\n", "\r", "\r\n"):
1888 raise ValueError("illegal newline value: %r" % (newline,))
1889
1890 self._readuniversal = not newline
1891 self._readtranslate = newline is None
1892 self._readnl = newline
1893 self._writetranslate = newline != ""
1894 self._writenl = newline or os.linesep
1895 self._pending = ""
1896 self._seennl = 0
1897
1898 # Reset the buffer first, in case __init__ is called
1899 # multiple times.
1900 self.truncate(0)
1901 if initial_value is None:
1902 initial_value = ""
1903 self.write(initial_value)
1904 self.seek(0)
1905
1906 @property
1907 def buffer(self):
1908 raise UnsupportedOperation("%s.buffer attribute is unsupported" %
1909 self.__class__.__name__)
1910
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +00001911 # XXX Cruft to support the TextIOWrapper API. This would only
1912 # be meaningful if StringIO supported the buffer attribute.
1913 # Hopefully, a better solution, than adding these pseudo-attributes,
1914 # will be found.
1915 @property
1916 def encoding(self):
1917 return "utf-8"
1918
1919 @property
1920 def errors(self):
1921 return "strict"
1922
1923 @property
1924 def line_buffering(self):
1925 return False
1926
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001927 def _decode_newlines(self, input, final=False):
1928 # decode input (with the eventual \r from a previous pass)
1929 if self._pending:
1930 input = self._pending + input
1931
1932 # retain last \r even when not translating data:
1933 # then readline() is sure to get \r\n in one pass
1934 if input.endswith("\r") and not final:
1935 input = input[:-1]
1936 self._pending = "\r"
1937 else:
1938 self._pending = ""
1939
1940 # Record which newlines are read
1941 crlf = input.count('\r\n')
1942 cr = input.count('\r') - crlf
1943 lf = input.count('\n') - crlf
1944 self._seennl |= (lf and self._LF) | (cr and self._CR) \
1945 | (crlf and self._CRLF)
1946
1947 if self._readtranslate:
1948 if crlf:
1949 output = input.replace("\r\n", "\n")
1950 if cr:
1951 output = input.replace("\r", "\n")
1952 else:
1953 output = input
1954
1955 return output
1956
1957 def writable(self):
1958 return True
1959
1960 def readable(self):
1961 return True
1962
1963 def seekable(self):
1964 return True
1965
1966 _read = _stringio._StringIO.read
1967 _write = _stringio._StringIO.write
1968 _tell = _stringio._StringIO.tell
1969 _seek = _stringio._StringIO.seek
1970 _truncate = _stringio._StringIO.truncate
1971 _getvalue = _stringio._StringIO.getvalue
1972
1973 def getvalue(self) -> str:
1974 """Retrieve the entire contents of the object."""
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001975 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001976 return self._getvalue()
1977
1978 def write(self, s: str) -> int:
1979 """Write string s to file.
1980
1981 Returns the number of characters written.
1982 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +00001983 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001984 if not isinstance(s, str):
1985 raise TypeError("can't write %s to text stream" %
1986 s.__class__.__name__)
1987 length = len(s)
1988 if self._writetranslate and self._writenl != "\n":
1989 s = s.replace("\n", self._writenl)
1990 self._pending = ""
1991 self._write(s)
1992 return length
1993
1994 def read(self, n: int = None) -> str:
1995 """Read at most n characters, returned as a string.
1996
1997 If the argument is negative or omitted, read until EOF
1998 is reached. Return an empty string at EOF.
1999 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +00002000 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002001 if n is None:
2002 n = -1
2003 res = self._pending
2004 if n < 0:
2005 res += self._decode_newlines(self._read(), True)
2006 self._pending = ""
2007 return res
2008 else:
2009 res = self._decode_newlines(self._read(n), True)
2010 self._pending = res[n:]
2011 return res[:n]
2012
2013 def tell(self) -> int:
2014 """Tell the current file position."""
Antoine Pitrou8043cf82009-01-09 19:54:29 +00002015 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002016 if self._pending:
2017 return self._tell() - len(self._pending)
2018 else:
2019 return self._tell()
2020
2021 def seek(self, pos: int = None, whence: int = 0) -> int:
2022 """Change stream position.
2023
2024 Seek to character offset pos relative to position indicated by whence:
2025 0 Start of stream (the default). pos should be >= 0;
2026 1 Current position - pos must be 0;
2027 2 End of stream - pos must be 0.
2028 Returns the new absolute position.
2029 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +00002030 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002031 self._pending = ""
2032 return self._seek(pos, whence)
2033
2034 def truncate(self, pos: int = None) -> int:
2035 """Truncate size to pos.
2036
2037 The pos argument defaults to the current file position, as
2038 returned by tell(). Imply an absolute seek to pos.
2039 Returns the new absolute position.
2040 """
Antoine Pitrou8043cf82009-01-09 19:54:29 +00002041 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002042 self._pending = ""
2043 return self._truncate(pos)
2044
2045 def readline(self, limit: int = None) -> str:
Antoine Pitrou8043cf82009-01-09 19:54:29 +00002046 self._checkClosed()
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00002047 if limit is None:
2048 limit = -1
2049 if limit >= 0:
2050 # XXX: Hack to support limit argument, for backwards
2051 # XXX compatibility
2052 line = self.readline()
2053 if len(line) <= limit:
2054 return line
2055 line, self._pending = line[:limit], line[limit:] + self._pending
2056 return line
2057
2058 line = self._pending
2059 self._pending = ""
2060
2061 start = 0
2062 pos = endpos = None
2063 while True:
2064 if self._readtranslate:
2065 # Newlines are already translated, only search for \n
2066 pos = line.find('\n', start)
2067 if pos >= 0:
2068 endpos = pos + 1
2069 break
2070 else:
2071 start = len(line)
2072
2073 elif self._readuniversal:
2074 # Universal newline search. Find any of \r, \r\n, \n
2075 # The decoder ensures that \r\n are not split in two pieces
2076
2077 # In C we'd look for these in parallel of course.
2078 nlpos = line.find("\n", start)
2079 crpos = line.find("\r", start)
2080 if crpos == -1:
2081 if nlpos == -1:
2082 # Nothing found
2083 start = len(line)
2084 else:
2085 # Found \n
2086 endpos = nlpos + 1
2087 break
2088 elif nlpos == -1:
2089 # Found lone \r
2090 endpos = crpos + 1
2091 break
2092 elif nlpos < crpos:
2093 # Found \n
2094 endpos = nlpos + 1
2095 break
2096 elif nlpos == crpos + 1:
2097 # Found \r\n
2098 endpos = crpos + 2
2099 break
2100 else:
2101 # Found \r
2102 endpos = crpos + 1
2103 break
2104 else:
2105 # non-universal
2106 pos = line.find(self._readnl)
2107 if pos >= 0:
2108 endpos = pos + len(self._readnl)
2109 break
2110
2111 # No line ending seen yet - get more data
2112 more_line = self.read(self._CHUNK_SIZE)
2113 if more_line:
2114 line += more_line
2115 else:
2116 # end of file
2117 return line
2118
2119 self._pending = line[endpos:]
2120 return line[:endpos]
2121
2122 _LF = 1
2123 _CR = 2
2124 _CRLF = 4
2125
2126 @property
2127 def newlines(self):
2128 return (None,
2129 "\n",
2130 "\r",
2131 ("\r", "\n"),
2132 "\r\n",
2133 ("\n", "\r\n"),
2134 ("\r", "\r\n"),
2135 ("\r", "\n", "\r\n")
2136 )[self._seennl]
2137
2138
2139except ImportError:
2140 StringIO = _StringIO