blob: 041e8ebd7134bef5c3a2dc1fb8cba613a32e0883 [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."""
Guido van Rossum53807da2007-04-10 19:01:47 +0000343 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000344
Guido van Rossum87429772007-04-10 21:06:59 +0000345 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000346 """Truncate file to size bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000347
Christian Heimes5d8da202008-05-06 13:58:24 +0000348 Size defaults to the current IO position as reported by tell(). Return
349 the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000350 """
351 self._unsupported("truncate")
352
353 ### Flush and close ###
354
355 def flush(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000356 """Flush write buffers, if applicable.
Guido van Rossum141f7672007-04-10 00:22:16 +0000357
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000358 This is not implemented for read-only and non-blocking streams.
Guido van Rossum141f7672007-04-10 00:22:16 +0000359 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000360 # XXX Should this return the number of bytes written???
Guido van Rossum141f7672007-04-10 00:22:16 +0000361
362 __closed = False
363
364 def close(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000365 """Flush and close the IO object.
Guido van Rossum141f7672007-04-10 00:22:16 +0000366
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000367 This method has no effect if the file is already closed.
Guido van Rossum141f7672007-04-10 00:22:16 +0000368 """
369 if not self.__closed:
Guido van Rossum469734b2007-07-10 12:00:45 +0000370 try:
371 self.flush()
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000372 except IOError:
373 pass # If flush() fails, just give up
374 self.__closed = True
Guido van Rossum141f7672007-04-10 00:22:16 +0000375
376 def __del__(self) -> None:
377 """Destructor. Calls close()."""
378 # The try/except block is in case this is called at program
379 # exit time, when it's possible that globals have already been
380 # deleted, and then the close() call might fail. Since
381 # there's nothing we can do about such failures and they annoy
382 # the end users, we suppress the traceback.
383 try:
384 self.close()
385 except:
386 pass
387
388 ### Inquiries ###
389
390 def seekable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000391 """Return whether object supports random access.
Guido van Rossum141f7672007-04-10 00:22:16 +0000392
393 If False, seek(), tell() and truncate() will raise IOError.
394 This method may need to do a test seek().
395 """
396 return False
397
Guido van Rossum5abbf752007-08-27 17:39:33 +0000398 def _checkSeekable(self, msg=None):
399 """Internal: raise an IOError if file is not seekable
400 """
401 if not self.seekable():
402 raise IOError("File or stream is not seekable."
403 if msg is None else msg)
404
405
Guido van Rossum141f7672007-04-10 00:22:16 +0000406 def readable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000407 """Return whether object was opened for reading.
Guido van Rossum141f7672007-04-10 00:22:16 +0000408
409 If False, read() will raise IOError.
410 """
411 return False
412
Guido van Rossum5abbf752007-08-27 17:39:33 +0000413 def _checkReadable(self, msg=None):
414 """Internal: raise an IOError if file is not readable
415 """
416 if not self.readable():
417 raise IOError("File or stream is not readable."
418 if msg is None else msg)
419
Guido van Rossum141f7672007-04-10 00:22:16 +0000420 def writable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000421 """Return whether object was opened for writing.
Guido van Rossum141f7672007-04-10 00:22:16 +0000422
423 If False, write() and truncate() will raise IOError.
424 """
425 return False
426
Guido van Rossum5abbf752007-08-27 17:39:33 +0000427 def _checkWritable(self, msg=None):
428 """Internal: raise an IOError if file is not writable
429 """
430 if not self.writable():
431 raise IOError("File or stream is not writable."
432 if msg is None else msg)
433
Guido van Rossum141f7672007-04-10 00:22:16 +0000434 @property
435 def closed(self):
436 """closed: bool. True iff the file has been closed.
437
438 For backwards compatibility, this is a property, not a predicate.
439 """
440 return self.__closed
441
Guido van Rossum5abbf752007-08-27 17:39:33 +0000442 def _checkClosed(self, msg=None):
443 """Internal: raise an ValueError if file is closed
444 """
445 if self.closed:
446 raise ValueError("I/O operation on closed file."
447 if msg is None else msg)
448
Guido van Rossum141f7672007-04-10 00:22:16 +0000449 ### Context manager ###
450
451 def __enter__(self) -> "IOBase": # That's a forward reference
452 """Context management protocol. Returns self."""
Christian Heimes3ecfea712008-02-09 20:51:34 +0000453 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000454 return self
455
456 def __exit__(self, *args) -> None:
457 """Context management protocol. Calls close()"""
458 self.close()
459
460 ### Lower-level APIs ###
461
462 # XXX Should these be present even if unimplemented?
463
464 def fileno(self) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000465 """Returns underlying file descriptor if one exists.
Guido van Rossum141f7672007-04-10 00:22:16 +0000466
Christian Heimes5d8da202008-05-06 13:58:24 +0000467 An IOError is raised if the IO object does not use a file descriptor.
Guido van Rossum141f7672007-04-10 00:22:16 +0000468 """
469 self._unsupported("fileno")
470
471 def isatty(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000472 """Return whether this is an 'interactive' stream.
473
474 Return False if it can't be determined.
Guido van Rossum141f7672007-04-10 00:22:16 +0000475 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000476 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000477 return False
478
Guido van Rossum7165cb12007-07-10 06:54:34 +0000479 ### Readline[s] and writelines ###
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000480
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000481 def readline(self, limit: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000482 r"""Read and return a line from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000483
484 If limit is specified, at most limit bytes will be read.
485
486 The line terminator is always b'\n' for binary files; for text
487 files, the newlines argument to open can be used to select the line
488 terminator(s) recognized.
489 """
490 # For backwards compatibility, a (slowish) readline().
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000491 self._checkClosed()
Guido van Rossum2bf71382007-06-08 00:07:57 +0000492 if hasattr(self, "peek"):
493 def nreadahead():
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000494 readahead = self.peek(1)
Guido van Rossum2bf71382007-06-08 00:07:57 +0000495 if not readahead:
496 return 1
497 n = (readahead.find(b"\n") + 1) or len(readahead)
498 if limit >= 0:
499 n = min(n, limit)
500 return n
501 else:
502 def nreadahead():
503 return 1
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000504 if limit is None:
505 limit = -1
Guido van Rossum254348e2007-11-21 19:29:53 +0000506 res = bytearray()
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000507 while limit < 0 or len(res) < limit:
Guido van Rossum2bf71382007-06-08 00:07:57 +0000508 b = self.read(nreadahead())
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000509 if not b:
510 break
511 res += b
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000512 if res.endswith(b"\n"):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000513 break
Guido van Rossum98297ee2007-11-06 21:34:58 +0000514 return bytes(res)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000515
Guido van Rossum7165cb12007-07-10 06:54:34 +0000516 def __iter__(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000517 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000518 return self
519
520 def __next__(self):
521 line = self.readline()
522 if not line:
523 raise StopIteration
524 return line
525
526 def readlines(self, hint=None):
Christian Heimes5d8da202008-05-06 13:58:24 +0000527 """Return a list of lines from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000528
529 hint can be specified to control the number of lines read: no more
530 lines will be read if the total size (in bytes/characters) of all
531 lines so far exceeds hint.
532 """
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000533 if hint is None or hint <= 0:
Guido van Rossum7165cb12007-07-10 06:54:34 +0000534 return list(self)
535 n = 0
536 lines = []
537 for line in self:
538 lines.append(line)
539 n += len(line)
540 if n >= hint:
541 break
542 return lines
543
544 def writelines(self, lines):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000545 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000546 for line in lines:
547 self.write(line)
548
Guido van Rossum141f7672007-04-10 00:22:16 +0000549
550class RawIOBase(IOBase):
551
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000552 """Base class for raw binary I/O."""
Guido van Rossum141f7672007-04-10 00:22:16 +0000553
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000554 # The read() method is implemented by calling readinto(); derived
555 # classes that want to support read() only need to implement
556 # readinto() as a primitive operation. In general, readinto() can be
557 # more efficient than read().
Guido van Rossum141f7672007-04-10 00:22:16 +0000558
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000559 # (It would be tempting to also provide an implementation of
560 # readinto() in terms of read(), in case the latter is a more suitable
561 # primitive operation, but that would lead to nasty recursion in case
562 # a subclass doesn't implement either.)
Guido van Rossum141f7672007-04-10 00:22:16 +0000563
Guido van Rossum7165cb12007-07-10 06:54:34 +0000564 def read(self, n: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000565 """Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000566
Georg Brandlf91197c2008-04-09 07:33:01 +0000567 Returns an empty bytes object on EOF, or None if the object is
Guido van Rossum01a27522007-03-07 01:00:12 +0000568 set not to block and has no data to read.
569 """
Guido van Rossum7165cb12007-07-10 06:54:34 +0000570 if n is None:
571 n = -1
572 if n < 0:
573 return self.readall()
Guido van Rossum254348e2007-11-21 19:29:53 +0000574 b = bytearray(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000575 n = self.readinto(b)
576 del b[n:]
Guido van Rossum98297ee2007-11-06 21:34:58 +0000577 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000578
Guido van Rossum7165cb12007-07-10 06:54:34 +0000579 def readall(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000580 """Read until EOF, using multiple read() call."""
Guido van Rossum254348e2007-11-21 19:29:53 +0000581 res = bytearray()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000582 while True:
583 data = self.read(DEFAULT_BUFFER_SIZE)
584 if not data:
585 break
586 res += data
Guido van Rossum98297ee2007-11-06 21:34:58 +0000587 return bytes(res)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000588
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000589 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000590 """Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000591
592 Returns number of bytes read (0 for EOF), or None if the object
593 is set not to block as has no data to read.
594 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000595 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000596
Guido van Rossum141f7672007-04-10 00:22:16 +0000597 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000598 """Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000599
Guido van Rossum78892e42007-04-06 17:31:18 +0000600 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000601 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000602 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000603
Guido van Rossum78892e42007-04-06 17:31:18 +0000604
Guido van Rossum141f7672007-04-10 00:22:16 +0000605class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000606
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000607 """Raw I/O implementation for OS files."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000608
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000609 # This multiply inherits from _FileIO and RawIOBase to make
610 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
611 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
612 # to do since _fileio.c is written in C).
Guido van Rossuma9e20242007-03-08 00:43:48 +0000613
Barry Warsaw40e82462008-11-20 20:14:50 +0000614 def __init__(self, name, mode="r", closefd=True):
615 _fileio._FileIO.__init__(self, name, mode, closefd)
616 self._name = name
617
Guido van Rossum87429772007-04-10 21:06:59 +0000618 def close(self):
619 _fileio._FileIO.close(self)
620 RawIOBase.close(self)
621
Guido van Rossum13633bb2007-04-13 18:42:35 +0000622 @property
623 def name(self):
624 return self._name
625
Guido van Rossuma9e20242007-03-08 00:43:48 +0000626
Guido van Rossumcce92b22007-04-10 14:41:39 +0000627class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000628
629 """Base class for buffered IO objects.
630
631 The main difference with RawIOBase is that the read() method
632 supports omitting the size argument, and does not have a default
633 implementation that defers to readinto().
634
635 In addition, read(), readinto() and write() may raise
636 BlockingIOError if the underlying raw stream is in non-blocking
637 mode and not ready; unlike their raw counterparts, they will never
638 return None.
639
640 A typical implementation should not inherit from a RawIOBase
641 implementation, but wrap one.
642 """
643
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000644 def read(self, n: int = None) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000645 """Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000646
Guido van Rossum024da5c2007-05-17 23:59:11 +0000647 If the argument is omitted, None, or negative, reads and
648 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000649
650 If the argument is positive, and the underlying raw stream is
651 not 'interactive', multiple raw reads may be issued to satisfy
652 the byte count (unless EOF is reached first). But for
653 interactive raw streams (XXX and for pipes?), at most one raw
654 read will be issued, and a short result does not imply that
655 EOF is imminent.
656
657 Returns an empty bytes array on EOF.
658
659 Raises BlockingIOError if the underlying raw stream has no
660 data at the moment.
661 """
662 self._unsupported("read")
663
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000664 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000665 """Read up to len(b) bytes into b.
Guido van Rossum141f7672007-04-10 00:22:16 +0000666
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000667 Like read(), this may issue multiple reads to the underlying raw
668 stream, unless the latter is 'interactive'.
Guido van Rossum141f7672007-04-10 00:22:16 +0000669
670 Returns the number of bytes read (0 for EOF).
671
672 Raises BlockingIOError if the underlying raw stream has no
673 data at the moment.
674 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000675 # XXX This ought to work with anything that supports the buffer API
Guido van Rossum87429772007-04-10 21:06:59 +0000676 data = self.read(len(b))
677 n = len(data)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000678 try:
679 b[:n] = data
680 except TypeError as err:
681 import array
682 if not isinstance(b, array.array):
683 raise err
684 b[:n] = array.array('b', data)
Guido van Rossum87429772007-04-10 21:06:59 +0000685 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000686
687 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000688 """Write the given buffer to the IO stream.
Guido van Rossum141f7672007-04-10 00:22:16 +0000689
Christian Heimes5d8da202008-05-06 13:58:24 +0000690 Return the number of bytes written, which is never less than
Guido van Rossum141f7672007-04-10 00:22:16 +0000691 len(b).
692
693 Raises BlockingIOError if the buffer is full and the
694 underlying raw stream cannot accept more data at the moment.
695 """
696 self._unsupported("write")
697
698
699class _BufferedIOMixin(BufferedIOBase):
700
701 """A mixin implementation of BufferedIOBase with an underlying raw stream.
702
703 This passes most requests on to the underlying raw stream. It
704 does *not* provide implementations of read(), readinto() or
705 write().
706 """
707
708 def __init__(self, raw):
709 self.raw = raw
710
711 ### Positioning ###
712
713 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000714 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000715
716 def tell(self):
717 return self.raw.tell()
718
719 def truncate(self, pos=None):
Guido van Rossum79b79ee2007-10-25 23:21:03 +0000720 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
721 # and a flush may be necessary to synch both views of the current
722 # file state.
723 self.flush()
Guido van Rossum57233cb2007-10-26 17:19:33 +0000724
725 if pos is None:
726 pos = self.tell()
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000727 # XXX: Should seek() be used, instead of passing the position
728 # XXX directly to truncate?
Guido van Rossum57233cb2007-10-26 17:19:33 +0000729 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000730
731 ### Flush and close ###
732
733 def flush(self):
734 self.raw.flush()
735
736 def close(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000737 if not self.closed:
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000738 try:
739 self.flush()
740 except IOError:
741 pass # If flush() fails, just give up
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000742 self.raw.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000743
744 ### Inquiries ###
745
746 def seekable(self):
747 return self.raw.seekable()
748
749 def readable(self):
750 return self.raw.readable()
751
752 def writable(self):
753 return self.raw.writable()
754
755 @property
756 def closed(self):
757 return self.raw.closed
758
Barry Warsaw40e82462008-11-20 20:14:50 +0000759 @property
760 def name(self):
761 return self.raw.name
762
763 @property
764 def mode(self):
765 return self.raw.mode
766
Guido van Rossum141f7672007-04-10 00:22:16 +0000767 ### Lower-level APIs ###
768
769 def fileno(self):
770 return self.raw.fileno()
771
772 def isatty(self):
773 return self.raw.isatty()
774
775
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000776class _BytesIO(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000777
Guido van Rossum024da5c2007-05-17 23:59:11 +0000778 """Buffered I/O implementation using an in-memory bytes buffer."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000779
Guido van Rossum024da5c2007-05-17 23:59:11 +0000780 def __init__(self, initial_bytes=None):
Guido van Rossum254348e2007-11-21 19:29:53 +0000781 buf = bytearray()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000782 if initial_bytes is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000783 buf += initial_bytes
784 self._buffer = buf
Guido van Rossum28524c72007-02-27 05:47:44 +0000785 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000786
787 def getvalue(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000788 """Return the bytes value (contents) of the buffer
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000789 """
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000790 if self.closed:
791 raise ValueError("getvalue on closed file")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000792 return bytes(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000793
Guido van Rossum024da5c2007-05-17 23:59:11 +0000794 def read(self, n=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000795 if self.closed:
796 raise ValueError("read from closed file")
Guido van Rossum024da5c2007-05-17 23:59:11 +0000797 if n is None:
798 n = -1
Guido van Rossum141f7672007-04-10 00:22:16 +0000799 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000800 n = len(self._buffer)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000801 if len(self._buffer) <= self._pos:
Alexandre Vassalotti2e0419d2008-05-07 00:09:04 +0000802 return b""
Guido van Rossum28524c72007-02-27 05:47:44 +0000803 newpos = min(len(self._buffer), self._pos + n)
804 b = self._buffer[self._pos : newpos]
805 self._pos = newpos
Guido van Rossum98297ee2007-11-06 21:34:58 +0000806 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000807
Guido van Rossum024da5c2007-05-17 23:59:11 +0000808 def read1(self, n):
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000809 """This is the same as read.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000810 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000811 return self.read(n)
812
Guido van Rossum28524c72007-02-27 05:47:44 +0000813 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000814 if self.closed:
815 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +0000816 if isinstance(b, str):
817 raise TypeError("can't write str to binary stream")
Guido van Rossum28524c72007-02-27 05:47:44 +0000818 n = len(b)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000819 if n == 0:
820 return 0
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000821 pos = self._pos
822 if pos > len(self._buffer):
Guido van Rossumb972a782007-07-21 00:25:15 +0000823 # Inserts null bytes between the current end of the file
824 # and the new write position.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000825 padding = b'\x00' * (pos - len(self._buffer))
826 self._buffer += padding
827 self._buffer[pos:pos + n] = b
828 self._pos += n
Guido van Rossum28524c72007-02-27 05:47:44 +0000829 return n
830
831 def seek(self, pos, whence=0):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000832 if self.closed:
833 raise ValueError("seek on closed file")
Christian Heimes3ab4f652007-11-09 01:27:29 +0000834 try:
835 pos = pos.__index__()
836 except AttributeError as err:
837 raise TypeError("an integer is required") from err
Guido van Rossum28524c72007-02-27 05:47:44 +0000838 if whence == 0:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000839 if pos < 0:
840 raise ValueError("negative seek position %r" % (pos,))
Alexandre Vassalottif0c0ff62008-05-09 21:21:21 +0000841 self._pos = pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000842 elif whence == 1:
843 self._pos = max(0, self._pos + pos)
844 elif whence == 2:
845 self._pos = max(0, len(self._buffer) + pos)
846 else:
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000847 raise ValueError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000848 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000849
850 def tell(self):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000851 if self.closed:
852 raise ValueError("tell on closed file")
Guido van Rossum28524c72007-02-27 05:47:44 +0000853 return self._pos
854
855 def truncate(self, pos=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000856 if self.closed:
857 raise ValueError("truncate on closed file")
Guido van Rossum28524c72007-02-27 05:47:44 +0000858 if pos is None:
859 pos = self._pos
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000860 elif pos < 0:
861 raise ValueError("negative truncate position %r" % (pos,))
Guido van Rossum28524c72007-02-27 05:47:44 +0000862 del self._buffer[pos:]
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000863 return self.seek(pos)
Guido van Rossum28524c72007-02-27 05:47:44 +0000864
865 def readable(self):
866 return True
867
868 def writable(self):
869 return True
870
871 def seekable(self):
872 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000873
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000874# Use the faster implementation of BytesIO if available
875try:
876 import _bytesio
877
878 class BytesIO(_bytesio._BytesIO, BufferedIOBase):
879 __doc__ = _bytesio._BytesIO.__doc__
880
881except ImportError:
882 BytesIO = _BytesIO
883
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000884
Guido van Rossum141f7672007-04-10 00:22:16 +0000885class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000886
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000887 """BufferedReader(raw[, buffer_size])
888
889 A buffer for a readable, sequential BaseRawIO object.
890
891 The constructor creates a BufferedReader for the given readable raw
892 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
893 is used.
894 """
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000895
Guido van Rossum78892e42007-04-06 17:31:18 +0000896 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000897 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000898 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000899 raw._checkReadable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000900 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum78892e42007-04-06 17:31:18 +0000901 self.buffer_size = buffer_size
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000902 self._reset_read_buf()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +0000903 self._read_lock = Lock()
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000904
905 def _reset_read_buf(self):
906 self._read_buf = b""
907 self._read_pos = 0
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000908
Guido van Rossum024da5c2007-05-17 23:59:11 +0000909 def read(self, n=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000910 """Read n bytes.
911
912 Returns exactly n bytes of data unless the underlying raw IO
Walter Dörwalda3270002007-05-29 19:13:29 +0000913 stream reaches EOF or if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000914 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000915 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000916 """
Antoine Pitrou87695762008-08-14 22:44:29 +0000917 with self._read_lock:
918 return self._read_unlocked(n)
919
920 def _read_unlocked(self, n=None):
Guido van Rossum78892e42007-04-06 17:31:18 +0000921 nodata_val = b""
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000922 empty_values = (b"", None)
923 buf = self._read_buf
924 pos = self._read_pos
925
926 # Special case for when the number of bytes to read is unspecified.
927 if n is None or n == -1:
928 self._reset_read_buf()
929 chunks = [buf[pos:]] # Strip the consumed bytes.
930 current_size = 0
931 while True:
932 # Read until EOF or until read() would block.
933 chunk = self.raw.read()
934 if chunk in empty_values:
935 nodata_val = chunk
936 break
937 current_size += len(chunk)
938 chunks.append(chunk)
939 return b"".join(chunks) or nodata_val
940
941 # The number of bytes to read is specified, return at most n bytes.
942 avail = len(buf) - pos # Length of the available buffered data.
943 if n <= avail:
944 # Fast path: the data to read is fully buffered.
945 self._read_pos += n
946 return buf[pos:pos+n]
947 # Slow path: read from the stream until enough bytes are read,
948 # or until an EOF occurs or until read() would block.
949 chunks = [buf[pos:]]
950 wanted = max(self.buffer_size, n)
951 while avail < n:
952 chunk = self.raw.read(wanted)
953 if chunk in empty_values:
954 nodata_val = chunk
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000955 break
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000956 avail += len(chunk)
957 chunks.append(chunk)
958 # n is more then avail only when an EOF occurred or when
959 # read() would have blocked.
960 n = min(n, avail)
961 out = b"".join(chunks)
962 self._read_buf = out[n:] # Save the extra data in the buffer.
963 self._read_pos = 0
964 return out[:n] if out else nodata_val
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000965
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000966 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000967 """Returns buffered bytes without advancing the position.
968
969 The argument indicates a desired minimal number of bytes; we
970 do at most one raw read to satisfy it. We never return more
971 than self.buffer_size.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000972 """
Antoine Pitrou87695762008-08-14 22:44:29 +0000973 with self._read_lock:
974 return self._peek_unlocked(n)
975
976 def _peek_unlocked(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000977 want = min(n, self.buffer_size)
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000978 have = len(self._read_buf) - self._read_pos
Guido van Rossum13633bb2007-04-13 18:42:35 +0000979 if have < want:
980 to_read = self.buffer_size - have
981 current = self.raw.read(to_read)
982 if current:
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000983 self._read_buf = self._read_buf[self._read_pos:] + current
984 self._read_pos = 0
985 return self._read_buf[self._read_pos:]
Guido van Rossum13633bb2007-04-13 18:42:35 +0000986
987 def read1(self, n):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000988 """Reads up to n bytes, with at most one read() system call."""
989 # Returns up to n bytes. If at least one byte is buffered, we
990 # only return buffered bytes. Otherwise, we do one raw read.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000991 if n <= 0:
992 return b""
Antoine Pitrou87695762008-08-14 22:44:29 +0000993 with self._read_lock:
994 self._peek_unlocked(1)
995 return self._read_unlocked(
996 min(n, len(self._read_buf) - self._read_pos))
Guido van Rossum13633bb2007-04-13 18:42:35 +0000997
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000998 def tell(self):
Antoine Pitrouc66f9092008-07-28 19:46:11 +0000999 return self.raw.tell() - len(self._read_buf) + self._read_pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001000
1001 def seek(self, pos, whence=0):
Antoine Pitrou87695762008-08-14 22:44:29 +00001002 with self._read_lock:
1003 if whence == 1:
1004 pos -= len(self._read_buf) - self._read_pos
1005 pos = self.raw.seek(pos, whence)
1006 self._reset_read_buf()
1007 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001008
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001009
Guido van Rossum141f7672007-04-10 00:22:16 +00001010class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001011
Christian Heimes5d8da202008-05-06 13:58:24 +00001012 """A buffer for a writeable sequential RawIO object.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001013
1014 The constructor creates a BufferedWriter for the given writeable raw
1015 stream. If the buffer_size is not given, it defaults to
1016 DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
1017 twice the buffer size.
1018 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001019
Guido van Rossum141f7672007-04-10 00:22:16 +00001020 def __init__(self, raw,
1021 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001022 raw._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001023 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001024 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +00001025 self.max_buffer_size = (2*buffer_size
1026 if max_buffer_size is None
1027 else max_buffer_size)
Guido van Rossum254348e2007-11-21 19:29:53 +00001028 self._write_buf = bytearray()
Antoine Pitroue1e48ea2008-08-15 00:05:08 +00001029 self._write_lock = Lock()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001030
1031 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001032 if self.closed:
1033 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +00001034 if isinstance(b, str):
1035 raise TypeError("can't write str to binary stream")
Antoine Pitrou87695762008-08-14 22:44:29 +00001036 with self._write_lock:
1037 # XXX we can implement some more tricks to try and avoid
1038 # partial writes
1039 if len(self._write_buf) > self.buffer_size:
1040 # We're full, so let's pre-flush the buffer
1041 try:
1042 self._flush_unlocked()
1043 except BlockingIOError as e:
1044 # We can't accept anything else.
1045 # XXX Why not just let the exception pass through?
1046 raise BlockingIOError(e.errno, e.strerror, 0)
1047 before = len(self._write_buf)
1048 self._write_buf.extend(b)
1049 written = len(self._write_buf) - before
1050 if len(self._write_buf) > self.buffer_size:
1051 try:
1052 self._flush_unlocked()
1053 except BlockingIOError as e:
1054 if len(self._write_buf) > self.max_buffer_size:
1055 # We've hit max_buffer_size. We have to accept a
1056 # partial write and cut back our buffer.
1057 overage = len(self._write_buf) - self.max_buffer_size
1058 self._write_buf = self._write_buf[:self.max_buffer_size]
1059 raise BlockingIOError(e.errno, e.strerror, overage)
1060 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001061
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001062 def truncate(self, pos=None):
Antoine Pitrou87695762008-08-14 22:44:29 +00001063 with self._write_lock:
1064 self._flush_unlocked()
1065 if pos is None:
1066 pos = self.raw.tell()
1067 return self.raw.truncate(pos)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001068
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001069 def flush(self):
Antoine Pitrou87695762008-08-14 22:44:29 +00001070 with self._write_lock:
1071 self._flush_unlocked()
1072
1073 def _flush_unlocked(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001074 if self.closed:
1075 raise ValueError("flush of closed file")
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001076 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +00001077 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001078 while self._write_buf:
1079 n = self.raw.write(self._write_buf)
1080 del self._write_buf[:n]
1081 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001082 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001083 n = e.characters_written
1084 del self._write_buf[:n]
1085 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +00001086 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001087
1088 def tell(self):
1089 return self.raw.tell() + len(self._write_buf)
1090
1091 def seek(self, pos, whence=0):
Antoine Pitrou87695762008-08-14 22:44:29 +00001092 with self._write_lock:
1093 self._flush_unlocked()
1094 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001095
Guido van Rossum01a27522007-03-07 01:00:12 +00001096
Guido van Rossum141f7672007-04-10 00:22:16 +00001097class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001098
Guido van Rossum01a27522007-03-07 01:00:12 +00001099 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001100
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001101 A buffered reader object and buffered writer object put together to
1102 form a sequential IO object that can read and write. This is typically
1103 used with a socket or two-way pipe.
Guido van Rossum78892e42007-04-06 17:31:18 +00001104
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001105 reader and writer are RawIOBase objects that are readable and
1106 writeable respectively. If the buffer_size is omitted it defaults to
1107 DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
1108 defaults to twice the buffer size.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001109 """
1110
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001111 # XXX The usefulness of this (compared to having two separate IO
1112 # objects) is questionable.
1113
Guido van Rossum141f7672007-04-10 00:22:16 +00001114 def __init__(self, reader, writer,
1115 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1116 """Constructor.
1117
1118 The arguments are two RawIO instances.
1119 """
Guido van Rossum5abbf752007-08-27 17:39:33 +00001120 reader._checkReadable()
1121 writer._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001122 self.reader = BufferedReader(reader, buffer_size)
1123 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001124
Guido van Rossum024da5c2007-05-17 23:59:11 +00001125 def read(self, n=None):
1126 if n is None:
1127 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001128 return self.reader.read(n)
1129
Guido van Rossum141f7672007-04-10 00:22:16 +00001130 def readinto(self, b):
1131 return self.reader.readinto(b)
1132
Guido van Rossum01a27522007-03-07 01:00:12 +00001133 def write(self, b):
1134 return self.writer.write(b)
1135
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001136 def peek(self, n=0):
1137 return self.reader.peek(n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001138
1139 def read1(self, n):
1140 return self.reader.read1(n)
1141
Guido van Rossum01a27522007-03-07 01:00:12 +00001142 def readable(self):
1143 return self.reader.readable()
1144
1145 def writable(self):
1146 return self.writer.writable()
1147
1148 def flush(self):
1149 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001150
Guido van Rossum01a27522007-03-07 01:00:12 +00001151 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +00001152 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +00001153 self.reader.close()
1154
1155 def isatty(self):
1156 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +00001157
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001158 @property
1159 def closed(self):
Guido van Rossum141f7672007-04-10 00:22:16 +00001160 return self.writer.closed()
Guido van Rossum01a27522007-03-07 01:00:12 +00001161
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001162
Guido van Rossum141f7672007-04-10 00:22:16 +00001163class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +00001164
Christian Heimes5d8da202008-05-06 13:58:24 +00001165 """A buffered interface to random access streams.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001166
1167 The constructor creates a reader and writer for a seekable stream,
1168 raw, given in the first argument. If the buffer_size is omitted it
1169 defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
1170 writer) defaults to twice the buffer size.
1171 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001172
Guido van Rossum141f7672007-04-10 00:22:16 +00001173 def __init__(self, raw,
1174 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001175 raw._checkSeekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001176 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001177 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1178
Guido van Rossum01a27522007-03-07 01:00:12 +00001179 def seek(self, pos, whence=0):
1180 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001181 # First do the raw seek, then empty the read buffer, so that
1182 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +00001183 pos = self.raw.seek(pos, whence)
Antoine Pitrou87695762008-08-14 22:44:29 +00001184 with self._read_lock:
1185 self._reset_read_buf()
Guido van Rossum53807da2007-04-10 19:01:47 +00001186 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +00001187
1188 def tell(self):
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001189 if self._write_buf:
Guido van Rossum01a27522007-03-07 01:00:12 +00001190 return self.raw.tell() + len(self._write_buf)
1191 else:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001192 return BufferedReader.tell(self)
Guido van Rossum01a27522007-03-07 01:00:12 +00001193
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001194 def truncate(self, pos=None):
1195 if pos is None:
1196 pos = self.tell()
1197 # Use seek to flush the read buffer.
1198 self.seek(pos)
1199 return BufferedWriter.truncate(self)
1200
Guido van Rossum024da5c2007-05-17 23:59:11 +00001201 def read(self, n=None):
1202 if n is None:
1203 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001204 self.flush()
1205 return BufferedReader.read(self, n)
1206
Guido van Rossum141f7672007-04-10 00:22:16 +00001207 def readinto(self, b):
1208 self.flush()
1209 return BufferedReader.readinto(self, b)
1210
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001211 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +00001212 self.flush()
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001213 return BufferedReader.peek(self, n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001214
1215 def read1(self, n):
1216 self.flush()
1217 return BufferedReader.read1(self, n)
1218
Guido van Rossum01a27522007-03-07 01:00:12 +00001219 def write(self, b):
Guido van Rossum78892e42007-04-06 17:31:18 +00001220 if self._read_buf:
Antoine Pitrouc66f9092008-07-28 19:46:11 +00001221 # Undo readahead
Antoine Pitrou87695762008-08-14 22:44:29 +00001222 with self._read_lock:
1223 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1224 self._reset_read_buf()
Guido van Rossum01a27522007-03-07 01:00:12 +00001225 return BufferedWriter.write(self, b)
1226
Guido van Rossum78892e42007-04-06 17:31:18 +00001227
Guido van Rossumcce92b22007-04-10 14:41:39 +00001228class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +00001229
1230 """Base class for text I/O.
1231
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001232 This class provides a character and line based interface to stream
1233 I/O. There is no readinto method because Python's character strings
1234 are immutable. There is no public constructor.
Guido van Rossum78892e42007-04-06 17:31:18 +00001235 """
1236
1237 def read(self, n: int = -1) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001238 """Read at most n characters from stream.
Guido van Rossum78892e42007-04-06 17:31:18 +00001239
1240 Read from underlying buffer until we have n characters or we hit EOF.
1241 If n is negative or omitted, read until EOF.
1242 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001243 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +00001244
Guido van Rossum9b76da62007-04-11 01:09:03 +00001245 def write(self, s: str) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001246 """Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001247 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +00001248
Guido van Rossum9b76da62007-04-11 01:09:03 +00001249 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +00001250 """Truncate size to pos."""
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001251 self._unsupported("truncate")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001252
Guido van Rossum78892e42007-04-06 17:31:18 +00001253 def readline(self) -> str:
Christian Heimes5d8da202008-05-06 13:58:24 +00001254 """Read until newline or EOF.
Guido van Rossum78892e42007-04-06 17:31:18 +00001255
1256 Returns an empty string if EOF is hit immediately.
1257 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001258 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +00001259
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001260 @property
1261 def encoding(self):
1262 """Subclasses should override."""
1263 return None
1264
Guido van Rossum8358db22007-08-18 21:39:55 +00001265 @property
1266 def newlines(self):
Christian Heimes5d8da202008-05-06 13:58:24 +00001267 """Line endings translated so far.
Guido van Rossum8358db22007-08-18 21:39:55 +00001268
1269 Only line endings translated during reading are considered.
1270
1271 Subclasses should override.
1272 """
1273 return None
1274
Guido van Rossum78892e42007-04-06 17:31:18 +00001275
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001276class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001277 r"""Codec used when reading a file in universal newlines mode. It wraps
1278 another incremental decoder, translating \r\n and \r into \n. It also
1279 records the types of newlines encountered. When used with
1280 translate=False, it ensures that the newline sequence is returned in
1281 one piece.
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001282 """
1283 def __init__(self, decoder, translate, errors='strict'):
1284 codecs.IncrementalDecoder.__init__(self, errors=errors)
1285 self.buffer = b''
1286 self.translate = translate
1287 self.decoder = decoder
1288 self.seennl = 0
1289
1290 def decode(self, input, final=False):
1291 # decode input (with the eventual \r from a previous pass)
1292 if self.buffer:
1293 input = self.buffer + input
1294
1295 output = self.decoder.decode(input, final=final)
1296
1297 # retain last \r even when not translating data:
1298 # then readline() is sure to get \r\n in one pass
1299 if output.endswith("\r") and not final:
1300 output = output[:-1]
1301 self.buffer = b'\r'
1302 else:
1303 self.buffer = b''
1304
1305 # Record which newlines are read
1306 crlf = output.count('\r\n')
1307 cr = output.count('\r') - crlf
1308 lf = output.count('\n') - crlf
1309 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1310 | (crlf and self._CRLF)
1311
1312 if self.translate:
1313 if crlf:
1314 output = output.replace("\r\n", "\n")
1315 if cr:
1316 output = output.replace("\r", "\n")
1317
1318 return output
1319
1320 def getstate(self):
1321 buf, flag = self.decoder.getstate()
1322 return buf + self.buffer, flag
1323
1324 def setstate(self, state):
1325 buf, flag = state
1326 if buf.endswith(b'\r'):
1327 self.buffer = b'\r'
1328 buf = buf[:-1]
1329 else:
1330 self.buffer = b''
1331 self.decoder.setstate((buf, flag))
1332
1333 def reset(self):
Alexandre Vassalottic3d7fe02007-12-28 01:24:22 +00001334 self.seennl = 0
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001335 self.buffer = b''
1336 self.decoder.reset()
1337
1338 _LF = 1
1339 _CR = 2
1340 _CRLF = 4
1341
1342 @property
1343 def newlines(self):
1344 return (None,
1345 "\n",
1346 "\r",
1347 ("\r", "\n"),
1348 "\r\n",
1349 ("\n", "\r\n"),
1350 ("\r", "\r\n"),
1351 ("\r", "\n", "\r\n")
1352 )[self.seennl]
1353
1354
Guido van Rossum78892e42007-04-06 17:31:18 +00001355class TextIOWrapper(TextIOBase):
1356
Christian Heimes5d8da202008-05-06 13:58:24 +00001357 r"""Character and line based layer over a BufferedIOBase object, buffer.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001358
1359 encoding gives the name of the encoding that the stream will be
1360 decoded or encoded with. It defaults to locale.getpreferredencoding.
1361
1362 errors determines the strictness of encoding and decoding (see the
1363 codecs.register) and defaults to "strict".
1364
1365 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1366 handling of line endings. If it is None, universal newlines is
1367 enabled. With this enabled, on input, the lines endings '\n', '\r',
1368 or '\r\n' are translated to '\n' before being returned to the
1369 caller. Conversely, on output, '\n' is translated to the system
1370 default line seperator, os.linesep. If newline is any other of its
1371 legal values, that newline becomes the newline when the file is read
1372 and it is returned untranslated. On output, '\n' is converted to the
1373 newline.
1374
1375 If line_buffering is True, a call to flush is implied when a call to
1376 write contains a newline character.
Guido van Rossum78892e42007-04-06 17:31:18 +00001377 """
1378
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001379 _CHUNK_SIZE = 128
Guido van Rossum78892e42007-04-06 17:31:18 +00001380
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001381 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1382 line_buffering=False):
Guido van Rossum8358db22007-08-18 21:39:55 +00001383 if newline not in (None, "", "\n", "\r", "\r\n"):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001384 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +00001385 if encoding is None:
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001386 try:
1387 encoding = os.device_encoding(buffer.fileno())
Brett Cannon041683d2007-10-11 23:08:53 +00001388 except (AttributeError, UnsupportedOperation):
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001389 pass
1390 if encoding is None:
Martin v. Löwisd78d3b42007-08-11 15:36:45 +00001391 try:
1392 import locale
1393 except ImportError:
1394 # Importing locale may fail if Python is being built
1395 encoding = "ascii"
1396 else:
1397 encoding = locale.getpreferredencoding()
Guido van Rossum78892e42007-04-06 17:31:18 +00001398
Christian Heimes8bd14fb2007-11-08 16:34:32 +00001399 if not isinstance(encoding, str):
1400 raise ValueError("invalid encoding: %r" % encoding)
1401
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001402 if errors is None:
1403 errors = "strict"
1404 else:
1405 if not isinstance(errors, str):
1406 raise ValueError("invalid errors: %r" % errors)
1407
Guido van Rossum78892e42007-04-06 17:31:18 +00001408 self.buffer = buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001409 self._line_buffering = line_buffering
Guido van Rossum78892e42007-04-06 17:31:18 +00001410 self._encoding = encoding
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001411 self._errors = errors
Guido van Rossum8358db22007-08-18 21:39:55 +00001412 self._readuniversal = not newline
1413 self._readtranslate = newline is None
1414 self._readnl = newline
1415 self._writetranslate = newline != ''
1416 self._writenl = newline or os.linesep
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001417 self._encoder = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001418 self._decoder = None
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001419 self._decoded_chars = '' # buffer for text returned from decoder
1420 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001421 self._snapshot = None # info for reconstructing decoder state
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001422 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001423
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001424 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1425 # where dec_flags is the second (integer) item of the decoder state
1426 # and next_input is the chunk of input bytes that comes next after the
1427 # snapshot point. We use this to reconstruct decoder states in tell().
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001428
1429 # Naming convention:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001430 # - "bytes_..." for integer variables that count input bytes
1431 # - "chars_..." for integer variables that count decoded characters
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001432
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001433 @property
1434 def encoding(self):
1435 return self._encoding
1436
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001437 @property
1438 def errors(self):
1439 return self._errors
1440
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001441 @property
1442 def line_buffering(self):
1443 return self._line_buffering
1444
Ka-Ping Yeeddaa7062008-03-17 20:35:15 +00001445 def seekable(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001446 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +00001447
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001448 def readable(self):
1449 return self.buffer.readable()
1450
1451 def writable(self):
1452 return self.buffer.writable()
1453
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001454 def flush(self):
1455 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001456 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001457
1458 def close(self):
Guido van Rossum33e7a8e2007-07-22 20:38:07 +00001459 try:
1460 self.flush()
1461 except:
1462 pass # If flush() fails, just give up
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001463 self.buffer.close()
1464
1465 @property
1466 def closed(self):
1467 return self.buffer.closed
1468
Barry Warsaw40e82462008-11-20 20:14:50 +00001469 @property
1470 def name(self):
1471 return self.buffer.name
1472
Guido van Rossum9be55972007-04-07 02:59:27 +00001473 def fileno(self):
1474 return self.buffer.fileno()
1475
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001476 def isatty(self):
1477 return self.buffer.isatty()
1478
Guido van Rossum78892e42007-04-06 17:31:18 +00001479 def write(self, s: str):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001480 if self.closed:
1481 raise ValueError("write to closed file")
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001482 if not isinstance(s, str):
Guido van Rossumdcce8392007-08-29 18:10:08 +00001483 raise TypeError("can't write %s to text stream" %
1484 s.__class__.__name__)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001485 length = len(s)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001486 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
Guido van Rossum8358db22007-08-18 21:39:55 +00001487 if haslf and self._writetranslate and self._writenl != "\n":
1488 s = s.replace("\n", self._writenl)
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001489 encoder = self._encoder or self._get_encoder()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001490 # XXX What if we were just reading?
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001491 b = encoder.encode(s)
Guido van Rossum8358db22007-08-18 21:39:55 +00001492 self.buffer.write(b)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001493 if self._line_buffering and (haslf or "\r" in s):
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001494 self.flush()
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001495 self._snapshot = None
1496 if self._decoder:
1497 self._decoder.reset()
1498 return length
Guido van Rossum78892e42007-04-06 17:31:18 +00001499
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001500 def _get_encoder(self):
1501 make_encoder = codecs.getincrementalencoder(self._encoding)
1502 self._encoder = make_encoder(self._errors)
1503 return self._encoder
1504
Guido van Rossum78892e42007-04-06 17:31:18 +00001505 def _get_decoder(self):
1506 make_decoder = codecs.getincrementaldecoder(self._encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001507 decoder = make_decoder(self._errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001508 if self._readuniversal:
1509 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1510 self._decoder = decoder
Guido van Rossum78892e42007-04-06 17:31:18 +00001511 return decoder
1512
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001513 # The following three methods implement an ADT for _decoded_chars.
1514 # Text returned from the decoder is buffered here until the client
1515 # requests it by calling our read() or readline() method.
1516 def _set_decoded_chars(self, chars):
1517 """Set the _decoded_chars buffer."""
1518 self._decoded_chars = chars
1519 self._decoded_chars_used = 0
1520
1521 def _get_decoded_chars(self, n=None):
1522 """Advance into the _decoded_chars buffer."""
1523 offset = self._decoded_chars_used
1524 if n is None:
1525 chars = self._decoded_chars[offset:]
1526 else:
1527 chars = self._decoded_chars[offset:offset + n]
1528 self._decoded_chars_used += len(chars)
1529 return chars
1530
1531 def _rewind_decoded_chars(self, n):
1532 """Rewind the _decoded_chars buffer."""
1533 if self._decoded_chars_used < n:
1534 raise AssertionError("rewind decoded_chars out of bounds")
1535 self._decoded_chars_used -= n
1536
Guido van Rossum9b76da62007-04-11 01:09:03 +00001537 def _read_chunk(self):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001538 """
1539 Read and decode the next chunk of data from the BufferedReader.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001540 """
1541
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001542 # The return value is True unless EOF was reached. The decoded
1543 # string is placed in self._decoded_chars (replacing its previous
1544 # value). The entire input chunk is sent to the decoder, though
1545 # some of it may remain buffered in the decoder, yet to be
1546 # converted.
1547
Guido van Rossum5abbf752007-08-27 17:39:33 +00001548 if self._decoder is None:
1549 raise ValueError("no decoder")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001550
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001551 if self._telling:
1552 # To prepare for tell(), we need to snapshot a point in the
1553 # file where the decoder's input buffer is empty.
Guido van Rossum9b76da62007-04-11 01:09:03 +00001554
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001555 dec_buffer, dec_flags = self._decoder.getstate()
1556 # Given this, we know there was a valid snapshot point
1557 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001558
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001559 # Read a chunk, decode it, and put the result in self._decoded_chars.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001560 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1561 eof = not input_chunk
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001562 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001563
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001564 if self._telling:
1565 # At the snapshot point, len(dec_buffer) bytes before the read,
1566 # the next input to be decoded is dec_buffer + input_chunk.
1567 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1568
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001569 return not eof
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001570
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001571 def _pack_cookie(self, position, dec_flags=0,
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001572 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001573 # The meaning of a tell() cookie is: seek to position, set the
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001574 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001575 # into the decoder with need_eof as the EOF flag, then skip
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001576 # chars_to_skip characters of the decoded result. For most simple
1577 # decoders, tell() will often just give a byte offset in the file.
1578 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1579 (chars_to_skip<<192) | bool(need_eof)<<256)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001580
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001581 def _unpack_cookie(self, bigint):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001582 rest, position = divmod(bigint, 1<<64)
1583 rest, dec_flags = divmod(rest, 1<<64)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001584 rest, bytes_to_feed = divmod(rest, 1<<64)
1585 need_eof, chars_to_skip = divmod(rest, 1<<64)
1586 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
Guido van Rossum9b76da62007-04-11 01:09:03 +00001587
1588 def tell(self):
1589 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001590 raise IOError("underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001591 if not self._telling:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001592 raise IOError("telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001593 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001594 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001595 decoder = self._decoder
1596 if decoder is None or self._snapshot is None:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001597 if self._decoded_chars:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001598 # This should never happen.
1599 raise AssertionError("pending decoded text")
Guido van Rossumcba608c2007-04-11 14:19:59 +00001600 return position
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001601
1602 # Skip backward to the snapshot point (see _read_chunk).
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001603 dec_flags, next_input = self._snapshot
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001604 position -= len(next_input)
1605
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001606 # How many decoded characters have been used up since the snapshot?
1607 chars_to_skip = self._decoded_chars_used
1608 if chars_to_skip == 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001609 # We haven't moved from the snapshot point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001610 return self._pack_cookie(position, dec_flags)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001611
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001612 # Starting from the snapshot position, we will walk the decoder
1613 # forward until it gives us enough decoded characters.
Guido van Rossumd76e7792007-04-17 02:38:04 +00001614 saved_state = decoder.getstate()
1615 try:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001616 # Note our initial start point.
1617 decoder.setstate((b'', dec_flags))
1618 start_pos = position
1619 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001620 need_eof = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001621
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001622 # Feed the decoder one byte at a time. As we go, note the
1623 # nearest "safe start point" before the current location
1624 # (a point where the decoder has nothing buffered, so seek()
1625 # can safely start from there and advance to this location).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001626 next_byte = bytearray(1)
1627 for next_byte[0] in next_input:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001628 bytes_fed += 1
1629 chars_decoded += len(decoder.decode(next_byte))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001630 dec_buffer, dec_flags = decoder.getstate()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001631 if not dec_buffer and chars_decoded <= chars_to_skip:
1632 # Decoder buffer is empty, so this is a safe start point.
1633 start_pos += bytes_fed
1634 chars_to_skip -= chars_decoded
1635 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1636 if chars_decoded >= chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001637 break
1638 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001639 # We didn't get enough decoded data; signal EOF to get more.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001640 chars_decoded += len(decoder.decode(b'', final=True))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001641 need_eof = 1
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001642 if chars_decoded < chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001643 raise IOError("can't reconstruct logical file position")
1644
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001645 # The returned cookie corresponds to the last safe start point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001646 return self._pack_cookie(
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001647 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001648 finally:
1649 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001650
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001651 def truncate(self, pos=None):
1652 self.flush()
1653 if pos is None:
1654 pos = self.tell()
1655 self.seek(pos)
1656 return self.buffer.truncate()
1657
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001658 def seek(self, cookie, whence=0):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001659 if self.closed:
1660 raise ValueError("tell on closed file")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001661 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001662 raise IOError("underlying stream is not seekable")
1663 if whence == 1: # seek relative to current position
1664 if cookie != 0:
1665 raise IOError("can't do nonzero cur-relative seeks")
1666 # Seeking to the current position should attempt to
1667 # sync the underlying buffer with the current position.
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001668 whence = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001669 cookie = self.tell()
1670 if whence == 2: # seek relative to end of file
1671 if cookie != 0:
1672 raise IOError("can't do nonzero end-relative seeks")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001673 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001674 position = self.buffer.seek(0, 2)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001675 self._set_decoded_chars('')
1676 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001677 if self._decoder:
1678 self._decoder.reset()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001679 return position
Guido van Rossum9b76da62007-04-11 01:09:03 +00001680 if whence != 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001681 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
Guido van Rossum9b76da62007-04-11 01:09:03 +00001682 (whence,))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001683 if cookie < 0:
1684 raise ValueError("negative seek position %r" % (cookie,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001685 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001686
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001687 # The strategy of seek() is to go back to the safe start point
1688 # and replay the effect of read(chars_to_skip) from there.
1689 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001690 self._unpack_cookie(cookie)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001691
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001692 # Seek back to the safe start point.
1693 self.buffer.seek(start_pos)
1694 self._set_decoded_chars('')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001695 self._snapshot = None
1696
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001697 # Restore the decoder to its state from the safe start point.
1698 if self._decoder or dec_flags or chars_to_skip:
1699 self._decoder = self._decoder or self._get_decoder()
1700 self._decoder.setstate((b'', dec_flags))
1701 self._snapshot = (dec_flags, b'')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001702
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001703 if chars_to_skip:
1704 # Just like _read_chunk, feed the decoder and save a snapshot.
1705 input_chunk = self.buffer.read(bytes_to_feed)
1706 self._set_decoded_chars(
1707 self._decoder.decode(input_chunk, need_eof))
1708 self._snapshot = (dec_flags, input_chunk)
1709
1710 # Skip chars_to_skip of the decoded characters.
1711 if len(self._decoded_chars) < chars_to_skip:
1712 raise IOError("can't restore logical file position")
1713 self._decoded_chars_used = chars_to_skip
1714
1715 return cookie
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001716
Guido van Rossum024da5c2007-05-17 23:59:11 +00001717 def read(self, n=None):
1718 if n is None:
1719 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001720 decoder = self._decoder or self._get_decoder()
Guido van Rossum78892e42007-04-06 17:31:18 +00001721 if n < 0:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001722 # Read everything.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001723 result = (self._get_decoded_chars() +
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001724 decoder.decode(self.buffer.read(), final=True))
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001725 self._set_decoded_chars('')
1726 self._snapshot = None
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001727 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001728 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001729 # Keep reading chunks until we have n characters to return.
1730 eof = False
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001731 result = self._get_decoded_chars(n)
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001732 while len(result) < n and not eof:
1733 eof = not self._read_chunk()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001734 result += self._get_decoded_chars(n - len(result))
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001735 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001736
Guido van Rossum024da5c2007-05-17 23:59:11 +00001737 def __next__(self):
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001738 self._telling = False
1739 line = self.readline()
1740 if not line:
1741 self._snapshot = None
1742 self._telling = self._seekable
1743 raise StopIteration
1744 return line
1745
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001746 def readline(self, limit=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001747 if self.closed:
1748 raise ValueError("read from closed file")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001749 if limit is None:
1750 limit = -1
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001751
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001752 # Grab all the decoded text (we will rewind any extra bits later).
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001753 line = self._get_decoded_chars()
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001754
Guido van Rossum78892e42007-04-06 17:31:18 +00001755 start = 0
1756 decoder = self._decoder or self._get_decoder()
1757
Guido van Rossum8358db22007-08-18 21:39:55 +00001758 pos = endpos = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001759 while True:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001760 if self._readtranslate:
1761 # Newlines are already translated, only search for \n
1762 pos = line.find('\n', start)
1763 if pos >= 0:
1764 endpos = pos + 1
1765 break
1766 else:
1767 start = len(line)
1768
1769 elif self._readuniversal:
Guido van Rossum8358db22007-08-18 21:39:55 +00001770 # Universal newline search. Find any of \r, \r\n, \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001771 # The decoder ensures that \r\n are not split in two pieces
Guido van Rossum78892e42007-04-06 17:31:18 +00001772
Guido van Rossum8358db22007-08-18 21:39:55 +00001773 # In C we'd look for these in parallel of course.
1774 nlpos = line.find("\n", start)
1775 crpos = line.find("\r", start)
1776 if crpos == -1:
1777 if nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001778 # Nothing found
Guido van Rossum8358db22007-08-18 21:39:55 +00001779 start = len(line)
Guido van Rossum78892e42007-04-06 17:31:18 +00001780 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001781 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001782 endpos = nlpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001783 break
1784 elif nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001785 # Found lone \r
1786 endpos = crpos + 1
1787 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001788 elif nlpos < crpos:
1789 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001790 endpos = nlpos + 1
Guido van Rossum78892e42007-04-06 17:31:18 +00001791 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001792 elif nlpos == crpos + 1:
1793 # Found \r\n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001794 endpos = crpos + 2
Guido van Rossum8358db22007-08-18 21:39:55 +00001795 break
1796 else:
1797 # Found \r
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001798 endpos = crpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001799 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001800 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001801 # non-universal
1802 pos = line.find(self._readnl)
1803 if pos >= 0:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001804 endpos = pos + len(self._readnl)
Guido van Rossum8358db22007-08-18 21:39:55 +00001805 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001806
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001807 if limit >= 0 and len(line) >= limit:
1808 endpos = limit # reached length limit
1809 break
1810
Guido van Rossum78892e42007-04-06 17:31:18 +00001811 # No line ending seen yet - get more data
Guido van Rossum8358db22007-08-18 21:39:55 +00001812 more_line = ''
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001813 while self._read_chunk():
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001814 if self._decoded_chars:
Guido van Rossum78892e42007-04-06 17:31:18 +00001815 break
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001816 if self._decoded_chars:
1817 line += self._get_decoded_chars()
Guido van Rossum8358db22007-08-18 21:39:55 +00001818 else:
1819 # end of file
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001820 self._set_decoded_chars('')
1821 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001822 return line
Guido van Rossum78892e42007-04-06 17:31:18 +00001823
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001824 if limit >= 0 and endpos > limit:
1825 endpos = limit # don't exceed limit
1826
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001827 # Rewind _decoded_chars to just after the line ending we found.
1828 self._rewind_decoded_chars(len(line) - endpos)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001829 return line[:endpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001830
Guido van Rossum8358db22007-08-18 21:39:55 +00001831 @property
1832 def newlines(self):
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001833 return self._decoder.newlines if self._decoder else None
Guido van Rossum024da5c2007-05-17 23:59:11 +00001834
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001835class _StringIO(TextIOWrapper):
1836 """Text I/O implementation using an in-memory buffer.
1837
1838 The initial_value argument sets the value of object. The newline
1839 argument is like the one of TextIOWrapper's constructor.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001840 """
Guido van Rossum024da5c2007-05-17 23:59:11 +00001841
1842 # XXX This is really slow, but fully functional
1843
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001844 def __init__(self, initial_value="", newline="\n"):
1845 super(_StringIO, self).__init__(BytesIO(),
1846 encoding="utf-8",
1847 errors="strict",
1848 newline=newline)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001849 if initial_value:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001850 if not isinstance(initial_value, str):
Guido van Rossum34d19282007-08-09 01:03:29 +00001851 initial_value = str(initial_value)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001852 self.write(initial_value)
1853 self.seek(0)
1854
1855 def getvalue(self):
Guido van Rossum34d19282007-08-09 01:03:29 +00001856 self.flush()
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001857 return self.buffer.getvalue().decode(self._encoding, self._errors)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001858
1859try:
1860 import _stringio
1861
1862 # This subclass is a reimplementation of the TextIOWrapper
1863 # interface without any of its text decoding facilities. All the
1864 # stored data is manipulated with the efficient
1865 # _stringio._StringIO extension type. Also, the newline decoding
1866 # mechanism of IncrementalNewlineDecoder is reimplemented here for
1867 # efficiency. Doing otherwise, would require us to implement a
1868 # fake decoder which would add an additional and unnecessary layer
1869 # on top of the _StringIO methods.
1870
1871 class StringIO(_stringio._StringIO, TextIOBase):
1872 """Text I/O implementation using an in-memory buffer.
1873
1874 The initial_value argument sets the value of object. The newline
1875 argument is like the one of TextIOWrapper's constructor.
1876 """
1877
1878 _CHUNK_SIZE = 4096
1879
1880 def __init__(self, initial_value="", newline="\n"):
1881 if newline not in (None, "", "\n", "\r", "\r\n"):
1882 raise ValueError("illegal newline value: %r" % (newline,))
1883
1884 self._readuniversal = not newline
1885 self._readtranslate = newline is None
1886 self._readnl = newline
1887 self._writetranslate = newline != ""
1888 self._writenl = newline or os.linesep
1889 self._pending = ""
1890 self._seennl = 0
1891
1892 # Reset the buffer first, in case __init__ is called
1893 # multiple times.
1894 self.truncate(0)
1895 if initial_value is None:
1896 initial_value = ""
1897 self.write(initial_value)
1898 self.seek(0)
1899
1900 @property
1901 def buffer(self):
1902 raise UnsupportedOperation("%s.buffer attribute is unsupported" %
1903 self.__class__.__name__)
1904
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +00001905 # XXX Cruft to support the TextIOWrapper API. This would only
1906 # be meaningful if StringIO supported the buffer attribute.
1907 # Hopefully, a better solution, than adding these pseudo-attributes,
1908 # will be found.
1909 @property
1910 def encoding(self):
1911 return "utf-8"
1912
1913 @property
1914 def errors(self):
1915 return "strict"
1916
1917 @property
1918 def line_buffering(self):
1919 return False
1920
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001921 def _decode_newlines(self, input, final=False):
1922 # decode input (with the eventual \r from a previous pass)
1923 if self._pending:
1924 input = self._pending + input
1925
1926 # retain last \r even when not translating data:
1927 # then readline() is sure to get \r\n in one pass
1928 if input.endswith("\r") and not final:
1929 input = input[:-1]
1930 self._pending = "\r"
1931 else:
1932 self._pending = ""
1933
1934 # Record which newlines are read
1935 crlf = input.count('\r\n')
1936 cr = input.count('\r') - crlf
1937 lf = input.count('\n') - crlf
1938 self._seennl |= (lf and self._LF) | (cr and self._CR) \
1939 | (crlf and self._CRLF)
1940
1941 if self._readtranslate:
1942 if crlf:
1943 output = input.replace("\r\n", "\n")
1944 if cr:
1945 output = input.replace("\r", "\n")
1946 else:
1947 output = input
1948
1949 return output
1950
1951 def writable(self):
1952 return True
1953
1954 def readable(self):
1955 return True
1956
1957 def seekable(self):
1958 return True
1959
1960 _read = _stringio._StringIO.read
1961 _write = _stringio._StringIO.write
1962 _tell = _stringio._StringIO.tell
1963 _seek = _stringio._StringIO.seek
1964 _truncate = _stringio._StringIO.truncate
1965 _getvalue = _stringio._StringIO.getvalue
1966
1967 def getvalue(self) -> str:
1968 """Retrieve the entire contents of the object."""
1969 if self.closed:
1970 raise ValueError("read on closed file")
1971 return self._getvalue()
1972
1973 def write(self, s: str) -> int:
1974 """Write string s to file.
1975
1976 Returns the number of characters written.
1977 """
1978 if self.closed:
1979 raise ValueError("write to closed file")
1980 if not isinstance(s, str):
1981 raise TypeError("can't write %s to text stream" %
1982 s.__class__.__name__)
1983 length = len(s)
1984 if self._writetranslate and self._writenl != "\n":
1985 s = s.replace("\n", self._writenl)
1986 self._pending = ""
1987 self._write(s)
1988 return length
1989
1990 def read(self, n: int = None) -> str:
1991 """Read at most n characters, returned as a string.
1992
1993 If the argument is negative or omitted, read until EOF
1994 is reached. Return an empty string at EOF.
1995 """
1996 if self.closed:
1997 raise ValueError("read to closed file")
1998 if n is None:
1999 n = -1
2000 res = self._pending
2001 if n < 0:
2002 res += self._decode_newlines(self._read(), True)
2003 self._pending = ""
2004 return res
2005 else:
2006 res = self._decode_newlines(self._read(n), True)
2007 self._pending = res[n:]
2008 return res[:n]
2009
2010 def tell(self) -> int:
2011 """Tell the current file position."""
2012 if self.closed:
2013 raise ValueError("tell from closed file")
2014 if self._pending:
2015 return self._tell() - len(self._pending)
2016 else:
2017 return self._tell()
2018
2019 def seek(self, pos: int = None, whence: int = 0) -> int:
2020 """Change stream position.
2021
2022 Seek to character offset pos relative to position indicated by whence:
2023 0 Start of stream (the default). pos should be >= 0;
2024 1 Current position - pos must be 0;
2025 2 End of stream - pos must be 0.
2026 Returns the new absolute position.
2027 """
2028 if self.closed:
2029 raise ValueError("seek from closed file")
2030 self._pending = ""
2031 return self._seek(pos, whence)
2032
2033 def truncate(self, pos: int = None) -> int:
2034 """Truncate size to pos.
2035
2036 The pos argument defaults to the current file position, as
2037 returned by tell(). Imply an absolute seek to pos.
2038 Returns the new absolute position.
2039 """
2040 if self.closed:
2041 raise ValueError("truncate from closed file")
2042 self._pending = ""
2043 return self._truncate(pos)
2044
2045 def readline(self, limit: int = None) -> str:
2046 if self.closed:
2047 raise ValueError("read from closed file")
2048 if limit is None:
2049 limit = -1
2050 if limit >= 0:
2051 # XXX: Hack to support limit argument, for backwards
2052 # XXX compatibility
2053 line = self.readline()
2054 if len(line) <= limit:
2055 return line
2056 line, self._pending = line[:limit], line[limit:] + self._pending
2057 return line
2058
2059 line = self._pending
2060 self._pending = ""
2061
2062 start = 0
2063 pos = endpos = None
2064 while True:
2065 if self._readtranslate:
2066 # Newlines are already translated, only search for \n
2067 pos = line.find('\n', start)
2068 if pos >= 0:
2069 endpos = pos + 1
2070 break
2071 else:
2072 start = len(line)
2073
2074 elif self._readuniversal:
2075 # Universal newline search. Find any of \r, \r\n, \n
2076 # The decoder ensures that \r\n are not split in two pieces
2077
2078 # In C we'd look for these in parallel of course.
2079 nlpos = line.find("\n", start)
2080 crpos = line.find("\r", start)
2081 if crpos == -1:
2082 if nlpos == -1:
2083 # Nothing found
2084 start = len(line)
2085 else:
2086 # Found \n
2087 endpos = nlpos + 1
2088 break
2089 elif nlpos == -1:
2090 # Found lone \r
2091 endpos = crpos + 1
2092 break
2093 elif nlpos < crpos:
2094 # Found \n
2095 endpos = nlpos + 1
2096 break
2097 elif nlpos == crpos + 1:
2098 # Found \r\n
2099 endpos = crpos + 2
2100 break
2101 else:
2102 # Found \r
2103 endpos = crpos + 1
2104 break
2105 else:
2106 # non-universal
2107 pos = line.find(self._readnl)
2108 if pos >= 0:
2109 endpos = pos + len(self._readnl)
2110 break
2111
2112 # No line ending seen yet - get more data
2113 more_line = self.read(self._CHUNK_SIZE)
2114 if more_line:
2115 line += more_line
2116 else:
2117 # end of file
2118 return line
2119
2120 self._pending = line[endpos:]
2121 return line[:endpos]
2122
2123 _LF = 1
2124 _CR = 2
2125 _CRLF = 4
2126
2127 @property
2128 def newlines(self):
2129 return (None,
2130 "\n",
2131 "\r",
2132 ("\r", "\n"),
2133 "\r\n",
2134 ("\n", "\r\n"),
2135 ("\r", "\r\n"),
2136 ("\r", "\n", "\r\n")
2137 )[self._seennl]
2138
2139
2140except ImportError:
2141 StringIO = _StringIO