blob: 4fe1e8cb68e58aa6aaf5ef8769941a45b0c3ac57 [file] [log] [blame]
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +00001"""The io module provides the Python interfaces to stream handling. The
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00002builtin open function is defined in this module.
3
4At the top of the I/O hierarchy is the abstract base class IOBase. It
5defines the basic interface to a stream. Note, however, that there is no
6seperation between reading and writing to streams; implementations are
7allowed to throw an IOError if they do not support a given operation.
8
9Extending IOBase is RawIOBase which deals simply with the reading and
10writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
11an interface to OS files.
12
13BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
14subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
15streams that are readable, writable, and both respectively.
16BufferedRandom provides a buffered interface to random access
17streams. BytesIO is a simple stream of in-memory bytes.
18
19Another IOBase subclass, TextIOBase, deals with the encoding and decoding
20of streams into text. TextIOWrapper, which extends it, is a buffered text
21interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
22is a in-memory stream for text.
23
24Argument names are not part of the specification, and only the arguments
25of open() are intended to be used as keyword arguments.
26
27data:
28
29DEFAULT_BUFFER_SIZE
30
31 An int containing the default buffer size used by the module's buffered
32 I/O classes. open() uses the file's blksize (as obtained by os.stat) if
33 possible.
34"""
35# New I/O library conforming to PEP 3116.
36
37# This is a prototype; hopefully eventually some of this will be
38# reimplemented in C.
39
40# XXX edge cases when switching between reading/writing
41# XXX need to support 1 meaning line-buffered
42# XXX whenever an argument is None, use the default value
43# XXX read/write ops should check readable/writable
44# XXX buffered readinto should work with arbitrary buffer objects
45# XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG
46# XXX check writable, readable and seekable in appropriate places
47
Guido van Rossum28524c72007-02-27 05:47:44 +000048
Guido van Rossum68bbcd22007-02-27 17:19:33 +000049__author__ = ("Guido van Rossum <guido@python.org>, "
Guido van Rossum78892e42007-04-06 17:31:18 +000050 "Mike Verdone <mike.verdone@gmail.com>, "
51 "Mark Russell <mark.russell@zen.co.uk>")
Guido van Rossum28524c72007-02-27 05:47:44 +000052
Guido van Rossum141f7672007-04-10 00:22:16 +000053__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
Guido van Rossum5abbf752007-08-27 17:39:33 +000054 "BytesIO", "StringIO", "BufferedIOBase",
Guido van Rossum01a27522007-03-07 01:00:12 +000055 "BufferedReader", "BufferedWriter", "BufferedRWPair",
Guido van Rossum141f7672007-04-10 00:22:16 +000056 "BufferedRandom", "TextIOBase", "TextIOWrapper"]
Guido van Rossum28524c72007-02-27 05:47:44 +000057
58import os
Guido van Rossumb7f136e2007-08-22 18:14:10 +000059import abc
Guido van Rossum78892e42007-04-06 17:31:18 +000060import sys
61import codecs
Guido van Rossum141f7672007-04-10 00:22:16 +000062import _fileio
Christian Heimesdeb75f52008-08-15 18:43:03 +000063# Import _thread instead of threading to reduce startup cost
64try:
65 from _thread import allocate_lock as Lock
66except ImportError:
67 from _dummy_thread import allocate_lock as Lock
68
Guido van Rossum28524c72007-02-27 05:47:44 +000069
Guido van Rossum5abbf752007-08-27 17:39:33 +000070# open() uses st_blksize whenever we can
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000071DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
Guido van Rossum01a27522007-03-07 01:00:12 +000072
73
Guido van Rossum141f7672007-04-10 00:22:16 +000074class BlockingIOError(IOError):
Guido van Rossum78892e42007-04-06 17:31:18 +000075
Guido van Rossum141f7672007-04-10 00:22:16 +000076 """Exception raised when I/O would block on a non-blocking I/O stream."""
77
78 def __init__(self, errno, strerror, characters_written=0):
Guido van Rossum01a27522007-03-07 01:00:12 +000079 IOError.__init__(self, errno, strerror)
80 self.characters_written = characters_written
81
Guido van Rossum68bbcd22007-02-27 17:19:33 +000082
Guido van Rossume7fc50f2007-12-03 22:54:21 +000083def open(file, mode="r", buffering=None, encoding=None, errors=None,
84 newline=None, closefd=True):
Christian Heimes5d8da202008-05-06 13:58:24 +000085
86 r"""Open file and return a stream. If the file cannot be opened, an IOError is
87 raised.
Guido van Rossum17e43e52007-02-27 15:45:13 +000088
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000089 file is either a string giving the name (and the path if the file
90 isn't in the current working directory) of the file to be opened or an
91 integer file descriptor of the file to be wrapped. (If a file
92 descriptor is given, it is closed when the returned I/O object is
93 closed, unless closefd is set to False.)
Guido van Rossum8358db22007-08-18 21:39:55 +000094
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000095 mode is an optional string that specifies the mode in which the file
96 is opened. It defaults to 'r' which means open for reading in text
97 mode. Other common values are 'w' for writing (truncating the file if
98 it already exists), and 'a' for appending (which on some Unix systems,
99 means that all writes append to the end of the file regardless of the
100 current seek position). In text mode, if encoding is not specified the
101 encoding used is platform dependent. (For reading and writing raw
102 bytes use binary mode and leave encoding unspecified.) The available
103 modes are:
Guido van Rossum8358db22007-08-18 21:39:55 +0000104
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000105 ========= ===============================================================
106 Character Meaning
107 --------- ---------------------------------------------------------------
108 'r' open for reading (default)
109 'w' open for writing, truncating the file first
110 'a' open for writing, appending to the end of the file if it exists
111 'b' binary mode
112 't' text mode (default)
113 '+' open a disk file for updating (reading and writing)
114 'U' universal newline mode (for backwards compatibility; unneeded
115 for new code)
116 ========= ===============================================================
Guido van Rossum17e43e52007-02-27 15:45:13 +0000117
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000118 The default mode is 'rt' (open for reading text). For binary random
119 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
120 'r+b' opens the file without truncation.
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000121
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000122 Python distinguishes between files opened in binary and text modes,
123 even when the underlying operating system doesn't. Files opened in
124 binary mode (appending 'b' to the mode argument) return contents as
125 bytes objects without any decoding. In text mode (the default, or when
126 't' is appended to the mode argument), the contents of the file are
127 returned as strings, the bytes having been first decoded using a
128 platform-dependent encoding or using the specified encoding if given.
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000129
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000130 buffering is an optional integer used to set the buffering policy. By
131 default full buffering is on. Pass 0 to switch buffering off (only
132 allowed in binary mode), 1 to set line buffering, and an integer > 1
133 for full buffering.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000134
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000135 encoding is the name of the encoding used to decode or encode the
136 file. This should only be used in text mode. The default encoding is
137 platform dependent, but any encoding supported by Python can be
138 passed. See the codecs module for the list of supported encodings.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000139
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000140 errors is an optional string that specifies how encoding errors are to
141 be handled---this argument should not be used in binary mode. Pass
142 'strict' to raise a ValueError exception if there is an encoding error
143 (the default of None has the same effect), or pass 'ignore' to ignore
144 errors. (Note that ignoring encoding errors can lead to data loss.)
145 See the documentation for codecs.register for a list of the permitted
146 encoding error strings.
147
148 newline controls how universal newlines works (it only applies to text
149 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
150 follows:
151
152 * On input, if newline is None, universal newlines mode is
153 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
154 these are translated into '\n' before being returned to the
155 caller. If it is '', universal newline mode is enabled, but line
156 endings are returned to the caller untranslated. If it has any of
157 the other legal values, input lines are only terminated by the given
158 string, and the line ending is returned to the caller untranslated.
159
160 * On output, if newline is None, any '\n' characters written are
161 translated to the system default line separator, os.linesep. If
162 newline is '', no translation takes place. If newline is any of the
163 other legal values, any '\n' characters written are translated to
164 the given string.
165
166 If closefd is False, the underlying file descriptor will be kept open
167 when the file is closed. This does not work when a file name is given
168 and must be True in that case.
169
170 open() returns a file object whose type depends on the mode, and
171 through which the standard file operations such as reading and writing
172 are performed. When open() is used to open a file in a text mode ('w',
173 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
174 a file in a binary mode, the returned class varies: in read binary
175 mode, it returns a BufferedReader; in write binary and append binary
176 modes, it returns a BufferedWriter, and in read/write mode, it returns
177 a BufferedRandom.
178
179 It is also possible to use a string or bytearray as a file for both
180 reading and writing. For strings StringIO can be used like a file
181 opened in a text mode, and for bytes a BytesIO can be used like a file
182 opened in a binary mode.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000183 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000184 if not isinstance(file, (str, int)):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000185 raise TypeError("invalid file: %r" % file)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000186 if not isinstance(mode, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000187 raise TypeError("invalid mode: %r" % mode)
188 if buffering is not None and not isinstance(buffering, int):
189 raise TypeError("invalid buffering: %r" % buffering)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000190 if encoding is not None and not isinstance(encoding, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000191 raise TypeError("invalid encoding: %r" % encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000192 if errors is not None and not isinstance(errors, str):
193 raise TypeError("invalid errors: %r" % errors)
Guido van Rossum28524c72007-02-27 05:47:44 +0000194 modes = set(mode)
Guido van Rossum9be55972007-04-07 02:59:27 +0000195 if modes - set("arwb+tU") or len(mode) > len(modes):
Guido van Rossum28524c72007-02-27 05:47:44 +0000196 raise ValueError("invalid mode: %r" % mode)
197 reading = "r" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000198 writing = "w" in modes
Guido van Rossum28524c72007-02-27 05:47:44 +0000199 appending = "a" in modes
200 updating = "+" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000201 text = "t" in modes
202 binary = "b" in modes
Guido van Rossum7165cb12007-07-10 06:54:34 +0000203 if "U" in modes:
204 if writing or appending:
205 raise ValueError("can't use U and writing mode at once")
Guido van Rossum9be55972007-04-07 02:59:27 +0000206 reading = True
Guido van Rossum28524c72007-02-27 05:47:44 +0000207 if text and binary:
208 raise ValueError("can't have text and binary mode at once")
209 if reading + writing + appending > 1:
210 raise ValueError("can't have read/write/append mode at once")
211 if not (reading or writing or appending):
212 raise ValueError("must have exactly one of read/write/append mode")
213 if binary and encoding is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +0000214 raise ValueError("binary mode doesn't take an encoding argument")
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000215 if binary and errors is not None:
216 raise ValueError("binary mode doesn't take an errors argument")
Guido van Rossum9b76da62007-04-11 01:09:03 +0000217 if binary and newline is not None:
218 raise ValueError("binary mode doesn't take a newline argument")
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000219 raw = FileIO(file,
Guido van Rossum28524c72007-02-27 05:47:44 +0000220 (reading and "r" or "") +
221 (writing and "w" or "") +
222 (appending and "a" or "") +
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000223 (updating and "+" or ""),
224 closefd)
Guido van Rossum28524c72007-02-27 05:47:44 +0000225 if buffering is None:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000226 buffering = -1
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000227 line_buffering = False
228 if buffering == 1 or buffering < 0 and raw.isatty():
229 buffering = -1
230 line_buffering = True
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000231 if buffering < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000232 buffering = DEFAULT_BUFFER_SIZE
Guido van Rossum17e43e52007-02-27 15:45:13 +0000233 try:
234 bs = os.fstat(raw.fileno()).st_blksize
235 except (os.error, AttributeError):
Guido van Rossumbb09b212007-03-18 03:36:28 +0000236 pass
237 else:
Guido van Rossum17e43e52007-02-27 15:45:13 +0000238 if bs > 1:
239 buffering = bs
Guido van Rossum28524c72007-02-27 05:47:44 +0000240 if buffering < 0:
241 raise ValueError("invalid buffering size")
242 if buffering == 0:
243 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000244 raw._name = file
245 raw._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000246 return raw
247 raise ValueError("can't have unbuffered text I/O")
248 if updating:
249 buffer = BufferedRandom(raw, buffering)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000250 elif writing or appending:
Guido van Rossum28524c72007-02-27 05:47:44 +0000251 buffer = BufferedWriter(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000252 elif reading:
Guido van Rossum28524c72007-02-27 05:47:44 +0000253 buffer = BufferedReader(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000254 else:
255 raise ValueError("unknown mode: %r" % mode)
Guido van Rossum28524c72007-02-27 05:47:44 +0000256 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000257 buffer.name = file
258 buffer.mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000259 return buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000260 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000261 text.name = file
262 text.mode = mode
263 return text
Guido van Rossum28524c72007-02-27 05:47:44 +0000264
Christian Heimesa33eb062007-12-08 17:47:40 +0000265class _DocDescriptor:
266 """Helper for builtins.open.__doc__
267 """
268 def __get__(self, obj, typ):
269 return (
270 "open(file, mode='r', buffering=None, encoding=None, "
271 "errors=None, newline=None, closefd=True)\n\n" +
272 open.__doc__)
Guido van Rossum28524c72007-02-27 05:47:44 +0000273
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000274class OpenWrapper:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000275 """Wrapper for builtins.open
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000276
277 Trick so that open won't become a bound method when stored
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000278 as a class variable (as dbm.dumb does).
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000279
280 See initstdio() in Python/pythonrun.c.
281 """
Christian Heimesa33eb062007-12-08 17:47:40 +0000282 __doc__ = _DocDescriptor()
283
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000284 def __new__(cls, *args, **kwargs):
285 return open(*args, **kwargs)
286
287
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000288class UnsupportedOperation(ValueError, IOError):
289 pass
290
291
Guido van Rossumb7f136e2007-08-22 18:14:10 +0000292class IOBase(metaclass=abc.ABCMeta):
Guido van Rossum28524c72007-02-27 05:47:44 +0000293
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000294 """The abstract base class for all I/O classes, acting on streams of
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000295 bytes. There is no public constructor.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000296
Guido van Rossum141f7672007-04-10 00:22:16 +0000297 This class provides dummy implementations for many methods that
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000298 derived classes can override selectively; the default implementations
299 represent a file that cannot be read, written or seeked.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000300
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000301 Even though IOBase does not declare read, readinto, or write because
302 their signatures will vary, implementations and clients should
303 consider those methods part of the interface. Also, implementations
304 may raise a IOError when operations they do not support are called.
Guido van Rossum53807da2007-04-10 19:01:47 +0000305
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000306 The basic type used for binary data read from or written to a file is
307 bytes. bytearrays are accepted too, and in some cases (such as
308 readinto) needed. Text I/O classes work with str data.
309
310 Note that calling any method (even inquiries) on a closed stream is
Benjamin Peterson9a89e962008-04-06 16:47:13 +0000311 undefined. Implementations may raise IOError in this case.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000312
313 IOBase (and its subclasses) support the iterator protocol, meaning
314 that an IOBase object can be iterated over yielding the lines in a
315 stream.
316
317 IOBase also supports the :keyword:`with` statement. In this example,
318 fp is closed after the suite of the with statment is complete:
319
320 with open('spam.txt', 'r') as fp:
321 fp.write('Spam and eggs!')
Guido van Rossum17e43e52007-02-27 15:45:13 +0000322 """
323
Guido van Rossum141f7672007-04-10 00:22:16 +0000324 ### Internal ###
325
326 def _unsupported(self, name: str) -> IOError:
327 """Internal: raise an exception for unsupported operations."""
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000328 raise UnsupportedOperation("%s.%s() not supported" %
329 (self.__class__.__name__, name))
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000330
Guido van Rossum141f7672007-04-10 00:22:16 +0000331 ### Positioning ###
332
Guido van Rossum53807da2007-04-10 19:01:47 +0000333 def seek(self, pos: int, whence: int = 0) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000334 """Change stream position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000335
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000336 Change the stream position to byte offset offset. offset is
337 interpreted relative to the position indicated by whence. Values
338 for whence are:
339
340 * 0 -- start of stream (the default); offset should be zero or positive
341 * 1 -- current stream position; offset may be negative
342 * 2 -- end of stream; offset is usually negative
343
344 Return the new absolute position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000345 """
346 self._unsupported("seek")
347
348 def tell(self) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000349 """Return current stream position."""
Guido van Rossum53807da2007-04-10 19:01:47 +0000350 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000351
Guido van Rossum87429772007-04-10 21:06:59 +0000352 def truncate(self, pos: int = None) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000353 """Truncate file to size bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000354
Christian Heimes5d8da202008-05-06 13:58:24 +0000355 Size defaults to the current IO position as reported by tell(). Return
356 the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000357 """
358 self._unsupported("truncate")
359
360 ### Flush and close ###
361
362 def flush(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000363 """Flush write buffers, if applicable.
Guido van Rossum141f7672007-04-10 00:22:16 +0000364
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000365 This is not implemented for read-only and non-blocking streams.
Guido van Rossum141f7672007-04-10 00:22:16 +0000366 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000367 # XXX Should this return the number of bytes written???
Guido van Rossum141f7672007-04-10 00:22:16 +0000368
369 __closed = False
370
371 def close(self) -> None:
Christian Heimes5d8da202008-05-06 13:58:24 +0000372 """Flush and close the IO object.
Guido van Rossum141f7672007-04-10 00:22:16 +0000373
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000374 This method has no effect if the file is already closed.
Guido van Rossum141f7672007-04-10 00:22:16 +0000375 """
376 if not self.__closed:
Guido van Rossum469734b2007-07-10 12:00:45 +0000377 try:
378 self.flush()
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000379 except IOError:
380 pass # If flush() fails, just give up
381 self.__closed = True
Guido van Rossum141f7672007-04-10 00:22:16 +0000382
383 def __del__(self) -> None:
384 """Destructor. Calls close()."""
385 # The try/except block is in case this is called at program
386 # exit time, when it's possible that globals have already been
387 # deleted, and then the close() call might fail. Since
388 # there's nothing we can do about such failures and they annoy
389 # the end users, we suppress the traceback.
390 try:
391 self.close()
392 except:
393 pass
394
395 ### Inquiries ###
396
397 def seekable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000398 """Return whether object supports random access.
Guido van Rossum141f7672007-04-10 00:22:16 +0000399
400 If False, seek(), tell() and truncate() will raise IOError.
401 This method may need to do a test seek().
402 """
403 return False
404
Guido van Rossum5abbf752007-08-27 17:39:33 +0000405 def _checkSeekable(self, msg=None):
406 """Internal: raise an IOError if file is not seekable
407 """
408 if not self.seekable():
409 raise IOError("File or stream is not seekable."
410 if msg is None else msg)
411
412
Guido van Rossum141f7672007-04-10 00:22:16 +0000413 def readable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000414 """Return whether object was opened for reading.
Guido van Rossum141f7672007-04-10 00:22:16 +0000415
416 If False, read() will raise IOError.
417 """
418 return False
419
Guido van Rossum5abbf752007-08-27 17:39:33 +0000420 def _checkReadable(self, msg=None):
421 """Internal: raise an IOError if file is not readable
422 """
423 if not self.readable():
424 raise IOError("File or stream is not readable."
425 if msg is None else msg)
426
Guido van Rossum141f7672007-04-10 00:22:16 +0000427 def writable(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000428 """Return whether object was opened for writing.
Guido van Rossum141f7672007-04-10 00:22:16 +0000429
430 If False, write() and truncate() will raise IOError.
431 """
432 return False
433
Guido van Rossum5abbf752007-08-27 17:39:33 +0000434 def _checkWritable(self, msg=None):
435 """Internal: raise an IOError if file is not writable
436 """
437 if not self.writable():
438 raise IOError("File or stream is not writable."
439 if msg is None else msg)
440
Guido van Rossum141f7672007-04-10 00:22:16 +0000441 @property
442 def closed(self):
443 """closed: bool. True iff the file has been closed.
444
445 For backwards compatibility, this is a property, not a predicate.
446 """
447 return self.__closed
448
Guido van Rossum5abbf752007-08-27 17:39:33 +0000449 def _checkClosed(self, msg=None):
450 """Internal: raise an ValueError if file is closed
451 """
452 if self.closed:
453 raise ValueError("I/O operation on closed file."
454 if msg is None else msg)
455
Guido van Rossum141f7672007-04-10 00:22:16 +0000456 ### Context manager ###
457
458 def __enter__(self) -> "IOBase": # That's a forward reference
459 """Context management protocol. Returns self."""
Christian Heimes3ecfea712008-02-09 20:51:34 +0000460 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000461 return self
462
463 def __exit__(self, *args) -> None:
464 """Context management protocol. Calls close()"""
465 self.close()
466
467 ### Lower-level APIs ###
468
469 # XXX Should these be present even if unimplemented?
470
471 def fileno(self) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000472 """Returns underlying file descriptor if one exists.
Guido van Rossum141f7672007-04-10 00:22:16 +0000473
Christian Heimes5d8da202008-05-06 13:58:24 +0000474 An IOError is raised if the IO object does not use a file descriptor.
Guido van Rossum141f7672007-04-10 00:22:16 +0000475 """
476 self._unsupported("fileno")
477
478 def isatty(self) -> bool:
Christian Heimes5d8da202008-05-06 13:58:24 +0000479 """Return whether this is an 'interactive' stream.
480
481 Return False if it can't be determined.
Guido van Rossum141f7672007-04-10 00:22:16 +0000482 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000483 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000484 return False
485
Guido van Rossum7165cb12007-07-10 06:54:34 +0000486 ### Readline[s] and writelines ###
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000487
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000488 def readline(self, limit: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000489 r"""Read and return a line from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000490
491 If limit is specified, at most limit bytes will be read.
492
493 The line terminator is always b'\n' for binary files; for text
494 files, the newlines argument to open can be used to select the line
495 terminator(s) recognized.
496 """
497 # For backwards compatibility, a (slowish) readline().
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000498 self._checkClosed()
Guido van Rossum2bf71382007-06-08 00:07:57 +0000499 if hasattr(self, "peek"):
500 def nreadahead():
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000501 readahead = self.peek(1)
Guido van Rossum2bf71382007-06-08 00:07:57 +0000502 if not readahead:
503 return 1
504 n = (readahead.find(b"\n") + 1) or len(readahead)
505 if limit >= 0:
506 n = min(n, limit)
507 return n
508 else:
509 def nreadahead():
510 return 1
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000511 if limit is None:
512 limit = -1
Guido van Rossum254348e2007-11-21 19:29:53 +0000513 res = bytearray()
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000514 while limit < 0 or len(res) < limit:
Guido van Rossum2bf71382007-06-08 00:07:57 +0000515 b = self.read(nreadahead())
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000516 if not b:
517 break
518 res += b
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000519 if res.endswith(b"\n"):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000520 break
Guido van Rossum98297ee2007-11-06 21:34:58 +0000521 return bytes(res)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000522
Guido van Rossum7165cb12007-07-10 06:54:34 +0000523 def __iter__(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000524 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000525 return self
526
527 def __next__(self):
528 line = self.readline()
529 if not line:
530 raise StopIteration
531 return line
532
533 def readlines(self, hint=None):
Christian Heimes5d8da202008-05-06 13:58:24 +0000534 """Return a list of lines from the stream.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000535
536 hint can be specified to control the number of lines read: no more
537 lines will be read if the total size (in bytes/characters) of all
538 lines so far exceeds hint.
539 """
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000540 if hint is None or hint <= 0:
Guido van Rossum7165cb12007-07-10 06:54:34 +0000541 return list(self)
542 n = 0
543 lines = []
544 for line in self:
545 lines.append(line)
546 n += len(line)
547 if n >= hint:
548 break
549 return lines
550
551 def writelines(self, lines):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000552 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000553 for line in lines:
554 self.write(line)
555
Guido van Rossum141f7672007-04-10 00:22:16 +0000556
557class RawIOBase(IOBase):
558
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000559 """Base class for raw binary I/O."""
Guido van Rossum141f7672007-04-10 00:22:16 +0000560
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000561 # The read() method is implemented by calling readinto(); derived
562 # classes that want to support read() only need to implement
563 # readinto() as a primitive operation. In general, readinto() can be
564 # more efficient than read().
Guido van Rossum141f7672007-04-10 00:22:16 +0000565
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000566 # (It would be tempting to also provide an implementation of
567 # readinto() in terms of read(), in case the latter is a more suitable
568 # primitive operation, but that would lead to nasty recursion in case
569 # a subclass doesn't implement either.)
Guido van Rossum141f7672007-04-10 00:22:16 +0000570
Guido van Rossum7165cb12007-07-10 06:54:34 +0000571 def read(self, n: int = -1) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000572 """Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000573
Georg Brandlf91197c2008-04-09 07:33:01 +0000574 Returns an empty bytes object on EOF, or None if the object is
Guido van Rossum01a27522007-03-07 01:00:12 +0000575 set not to block and has no data to read.
576 """
Guido van Rossum7165cb12007-07-10 06:54:34 +0000577 if n is None:
578 n = -1
579 if n < 0:
580 return self.readall()
Guido van Rossum254348e2007-11-21 19:29:53 +0000581 b = bytearray(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000582 n = self.readinto(b)
583 del b[n:]
Guido van Rossum98297ee2007-11-06 21:34:58 +0000584 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000585
Guido van Rossum7165cb12007-07-10 06:54:34 +0000586 def readall(self):
Christian Heimes5d8da202008-05-06 13:58:24 +0000587 """Read until EOF, using multiple read() call."""
Guido van Rossum254348e2007-11-21 19:29:53 +0000588 res = bytearray()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000589 while True:
590 data = self.read(DEFAULT_BUFFER_SIZE)
591 if not data:
592 break
593 res += data
Guido van Rossum98297ee2007-11-06 21:34:58 +0000594 return bytes(res)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000595
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000596 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000597 """Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000598
599 Returns number of bytes read (0 for EOF), or None if the object
600 is set not to block as has no data to read.
601 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000602 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000603
Guido van Rossum141f7672007-04-10 00:22:16 +0000604 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000605 """Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000606
Guido van Rossum78892e42007-04-06 17:31:18 +0000607 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000608 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000609 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000610
Guido van Rossum78892e42007-04-06 17:31:18 +0000611
Guido van Rossum141f7672007-04-10 00:22:16 +0000612class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000613
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000614 """Raw I/O implementation for OS files."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000615
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000616 # This multiply inherits from _FileIO and RawIOBase to make
617 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
618 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
619 # to do since _fileio.c is written in C).
Guido van Rossuma9e20242007-03-08 00:43:48 +0000620
Guido van Rossum87429772007-04-10 21:06:59 +0000621 def close(self):
622 _fileio._FileIO.close(self)
623 RawIOBase.close(self)
624
Guido van Rossum13633bb2007-04-13 18:42:35 +0000625 @property
626 def name(self):
627 return self._name
628
Georg Brandlf91197c2008-04-09 07:33:01 +0000629 # XXX(gb): _FileIO already has a mode property
Guido van Rossum13633bb2007-04-13 18:42:35 +0000630 @property
631 def mode(self):
632 return self._mode
633
Guido van Rossuma9e20242007-03-08 00:43:48 +0000634
Guido van Rossumcce92b22007-04-10 14:41:39 +0000635class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000636
637 """Base class for buffered IO objects.
638
639 The main difference with RawIOBase is that the read() method
640 supports omitting the size argument, and does not have a default
641 implementation that defers to readinto().
642
643 In addition, read(), readinto() and write() may raise
644 BlockingIOError if the underlying raw stream is in non-blocking
645 mode and not ready; unlike their raw counterparts, they will never
646 return None.
647
648 A typical implementation should not inherit from a RawIOBase
649 implementation, but wrap one.
650 """
651
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000652 def read(self, n: int = None) -> bytes:
Christian Heimes5d8da202008-05-06 13:58:24 +0000653 """Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000654
Guido van Rossum024da5c2007-05-17 23:59:11 +0000655 If the argument is omitted, None, or negative, reads and
656 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000657
658 If the argument is positive, and the underlying raw stream is
659 not 'interactive', multiple raw reads may be issued to satisfy
660 the byte count (unless EOF is reached first). But for
661 interactive raw streams (XXX and for pipes?), at most one raw
662 read will be issued, and a short result does not imply that
663 EOF is imminent.
664
665 Returns an empty bytes array on EOF.
666
667 Raises BlockingIOError if the underlying raw stream has no
668 data at the moment.
669 """
670 self._unsupported("read")
671
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000672 def readinto(self, b: bytearray) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000673 """Read up to len(b) bytes into b.
Guido van Rossum141f7672007-04-10 00:22:16 +0000674
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000675 Like read(), this may issue multiple reads to the underlying raw
676 stream, unless the latter is 'interactive'.
Guido van Rossum141f7672007-04-10 00:22:16 +0000677
678 Returns the number of bytes read (0 for EOF).
679
680 Raises BlockingIOError if the underlying raw stream has no
681 data at the moment.
682 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000683 # XXX This ought to work with anything that supports the buffer API
Guido van Rossum87429772007-04-10 21:06:59 +0000684 data = self.read(len(b))
685 n = len(data)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000686 try:
687 b[:n] = data
688 except TypeError as err:
689 import array
690 if not isinstance(b, array.array):
691 raise err
692 b[:n] = array.array('b', data)
Guido van Rossum87429772007-04-10 21:06:59 +0000693 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000694
695 def write(self, b: bytes) -> int:
Christian Heimes5d8da202008-05-06 13:58:24 +0000696 """Write the given buffer to the IO stream.
Guido van Rossum141f7672007-04-10 00:22:16 +0000697
Christian Heimes5d8da202008-05-06 13:58:24 +0000698 Return the number of bytes written, which is never less than
Guido van Rossum141f7672007-04-10 00:22:16 +0000699 len(b).
700
701 Raises BlockingIOError if the buffer is full and the
702 underlying raw stream cannot accept more data at the moment.
703 """
704 self._unsupported("write")
705
706
707class _BufferedIOMixin(BufferedIOBase):
708
709 """A mixin implementation of BufferedIOBase with an underlying raw stream.
710
711 This passes most requests on to the underlying raw stream. It
712 does *not* provide implementations of read(), readinto() or
713 write().
714 """
715
716 def __init__(self, raw):
717 self.raw = raw
718
719 ### Positioning ###
720
721 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000722 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000723
724 def tell(self):
725 return self.raw.tell()
726
727 def truncate(self, pos=None):
Guido van Rossum79b79ee2007-10-25 23:21:03 +0000728 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
729 # and a flush may be necessary to synch both views of the current
730 # file state.
731 self.flush()
Guido van Rossum57233cb2007-10-26 17:19:33 +0000732
733 if pos is None:
734 pos = self.tell()
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000735 # XXX: Should seek() be used, instead of passing the position
736 # XXX directly to truncate?
Guido van Rossum57233cb2007-10-26 17:19:33 +0000737 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000738
739 ### Flush and close ###
740
741 def flush(self):
742 self.raw.flush()
743
744 def close(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000745 if not self.closed:
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000746 try:
747 self.flush()
748 except IOError:
749 pass # If flush() fails, just give up
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000750 self.raw.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000751
752 ### Inquiries ###
753
754 def seekable(self):
755 return self.raw.seekable()
756
757 def readable(self):
758 return self.raw.readable()
759
760 def writable(self):
761 return self.raw.writable()
762
763 @property
764 def closed(self):
765 return self.raw.closed
766
767 ### 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
Guido van Rossum9be55972007-04-07 02:59:27 +00001469 def fileno(self):
1470 return self.buffer.fileno()
1471
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001472 def isatty(self):
1473 return self.buffer.isatty()
1474
Guido van Rossum78892e42007-04-06 17:31:18 +00001475 def write(self, s: str):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001476 if self.closed:
1477 raise ValueError("write to closed file")
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001478 if not isinstance(s, str):
Guido van Rossumdcce8392007-08-29 18:10:08 +00001479 raise TypeError("can't write %s to text stream" %
1480 s.__class__.__name__)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001481 length = len(s)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001482 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
Guido van Rossum8358db22007-08-18 21:39:55 +00001483 if haslf and self._writetranslate and self._writenl != "\n":
1484 s = s.replace("\n", self._writenl)
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001485 encoder = self._encoder or self._get_encoder()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001486 # XXX What if we were just reading?
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001487 b = encoder.encode(s)
Guido van Rossum8358db22007-08-18 21:39:55 +00001488 self.buffer.write(b)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001489 if self._line_buffering and (haslf or "\r" in s):
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001490 self.flush()
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001491 self._snapshot = None
1492 if self._decoder:
1493 self._decoder.reset()
1494 return length
Guido van Rossum78892e42007-04-06 17:31:18 +00001495
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001496 def _get_encoder(self):
1497 make_encoder = codecs.getincrementalencoder(self._encoding)
1498 self._encoder = make_encoder(self._errors)
1499 return self._encoder
1500
Guido van Rossum78892e42007-04-06 17:31:18 +00001501 def _get_decoder(self):
1502 make_decoder = codecs.getincrementaldecoder(self._encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001503 decoder = make_decoder(self._errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001504 if self._readuniversal:
1505 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1506 self._decoder = decoder
Guido van Rossum78892e42007-04-06 17:31:18 +00001507 return decoder
1508
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001509 # The following three methods implement an ADT for _decoded_chars.
1510 # Text returned from the decoder is buffered here until the client
1511 # requests it by calling our read() or readline() method.
1512 def _set_decoded_chars(self, chars):
1513 """Set the _decoded_chars buffer."""
1514 self._decoded_chars = chars
1515 self._decoded_chars_used = 0
1516
1517 def _get_decoded_chars(self, n=None):
1518 """Advance into the _decoded_chars buffer."""
1519 offset = self._decoded_chars_used
1520 if n is None:
1521 chars = self._decoded_chars[offset:]
1522 else:
1523 chars = self._decoded_chars[offset:offset + n]
1524 self._decoded_chars_used += len(chars)
1525 return chars
1526
1527 def _rewind_decoded_chars(self, n):
1528 """Rewind the _decoded_chars buffer."""
1529 if self._decoded_chars_used < n:
1530 raise AssertionError("rewind decoded_chars out of bounds")
1531 self._decoded_chars_used -= n
1532
Guido van Rossum9b76da62007-04-11 01:09:03 +00001533 def _read_chunk(self):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001534 """
1535 Read and decode the next chunk of data from the BufferedReader.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001536 """
1537
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001538 # The return value is True unless EOF was reached. The decoded
1539 # string is placed in self._decoded_chars (replacing its previous
1540 # value). The entire input chunk is sent to the decoder, though
1541 # some of it may remain buffered in the decoder, yet to be
1542 # converted.
1543
Guido van Rossum5abbf752007-08-27 17:39:33 +00001544 if self._decoder is None:
1545 raise ValueError("no decoder")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001546
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001547 if self._telling:
1548 # To prepare for tell(), we need to snapshot a point in the
1549 # file where the decoder's input buffer is empty.
Guido van Rossum9b76da62007-04-11 01:09:03 +00001550
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001551 dec_buffer, dec_flags = self._decoder.getstate()
1552 # Given this, we know there was a valid snapshot point
1553 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001554
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001555 # Read a chunk, decode it, and put the result in self._decoded_chars.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001556 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1557 eof = not input_chunk
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001558 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001559
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001560 if self._telling:
1561 # At the snapshot point, len(dec_buffer) bytes before the read,
1562 # the next input to be decoded is dec_buffer + input_chunk.
1563 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1564
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001565 return not eof
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001566
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001567 def _pack_cookie(self, position, dec_flags=0,
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001568 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001569 # The meaning of a tell() cookie is: seek to position, set the
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001570 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001571 # into the decoder with need_eof as the EOF flag, then skip
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001572 # chars_to_skip characters of the decoded result. For most simple
1573 # decoders, tell() will often just give a byte offset in the file.
1574 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1575 (chars_to_skip<<192) | bool(need_eof)<<256)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001576
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001577 def _unpack_cookie(self, bigint):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001578 rest, position = divmod(bigint, 1<<64)
1579 rest, dec_flags = divmod(rest, 1<<64)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001580 rest, bytes_to_feed = divmod(rest, 1<<64)
1581 need_eof, chars_to_skip = divmod(rest, 1<<64)
1582 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
Guido van Rossum9b76da62007-04-11 01:09:03 +00001583
1584 def tell(self):
1585 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001586 raise IOError("underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001587 if not self._telling:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001588 raise IOError("telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001589 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001590 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001591 decoder = self._decoder
1592 if decoder is None or self._snapshot is None:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001593 if self._decoded_chars:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001594 # This should never happen.
1595 raise AssertionError("pending decoded text")
Guido van Rossumcba608c2007-04-11 14:19:59 +00001596 return position
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001597
1598 # Skip backward to the snapshot point (see _read_chunk).
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001599 dec_flags, next_input = self._snapshot
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001600 position -= len(next_input)
1601
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001602 # How many decoded characters have been used up since the snapshot?
1603 chars_to_skip = self._decoded_chars_used
1604 if chars_to_skip == 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001605 # We haven't moved from the snapshot point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001606 return self._pack_cookie(position, dec_flags)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001607
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001608 # Starting from the snapshot position, we will walk the decoder
1609 # forward until it gives us enough decoded characters.
Guido van Rossumd76e7792007-04-17 02:38:04 +00001610 saved_state = decoder.getstate()
1611 try:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001612 # Note our initial start point.
1613 decoder.setstate((b'', dec_flags))
1614 start_pos = position
1615 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001616 need_eof = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001617
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001618 # Feed the decoder one byte at a time. As we go, note the
1619 # nearest "safe start point" before the current location
1620 # (a point where the decoder has nothing buffered, so seek()
1621 # can safely start from there and advance to this location).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001622 next_byte = bytearray(1)
1623 for next_byte[0] in next_input:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001624 bytes_fed += 1
1625 chars_decoded += len(decoder.decode(next_byte))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001626 dec_buffer, dec_flags = decoder.getstate()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001627 if not dec_buffer and chars_decoded <= chars_to_skip:
1628 # Decoder buffer is empty, so this is a safe start point.
1629 start_pos += bytes_fed
1630 chars_to_skip -= chars_decoded
1631 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1632 if chars_decoded >= chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001633 break
1634 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001635 # We didn't get enough decoded data; signal EOF to get more.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001636 chars_decoded += len(decoder.decode(b'', final=True))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001637 need_eof = 1
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001638 if chars_decoded < chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001639 raise IOError("can't reconstruct logical file position")
1640
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001641 # The returned cookie corresponds to the last safe start point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001642 return self._pack_cookie(
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001643 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001644 finally:
1645 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001646
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001647 def truncate(self, pos=None):
1648 self.flush()
1649 if pos is None:
1650 pos = self.tell()
1651 self.seek(pos)
1652 return self.buffer.truncate()
1653
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001654 def seek(self, cookie, whence=0):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001655 if self.closed:
1656 raise ValueError("tell on closed file")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001657 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001658 raise IOError("underlying stream is not seekable")
1659 if whence == 1: # seek relative to current position
1660 if cookie != 0:
1661 raise IOError("can't do nonzero cur-relative seeks")
1662 # Seeking to the current position should attempt to
1663 # sync the underlying buffer with the current position.
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001664 whence = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001665 cookie = self.tell()
1666 if whence == 2: # seek relative to end of file
1667 if cookie != 0:
1668 raise IOError("can't do nonzero end-relative seeks")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001669 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001670 position = self.buffer.seek(0, 2)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001671 self._set_decoded_chars('')
1672 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001673 if self._decoder:
1674 self._decoder.reset()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001675 return position
Guido van Rossum9b76da62007-04-11 01:09:03 +00001676 if whence != 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001677 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
Guido van Rossum9b76da62007-04-11 01:09:03 +00001678 (whence,))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001679 if cookie < 0:
1680 raise ValueError("negative seek position %r" % (cookie,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001681 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001682
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001683 # The strategy of seek() is to go back to the safe start point
1684 # and replay the effect of read(chars_to_skip) from there.
1685 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001686 self._unpack_cookie(cookie)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001687
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001688 # Seek back to the safe start point.
1689 self.buffer.seek(start_pos)
1690 self._set_decoded_chars('')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001691 self._snapshot = None
1692
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001693 # Restore the decoder to its state from the safe start point.
1694 if self._decoder or dec_flags or chars_to_skip:
1695 self._decoder = self._decoder or self._get_decoder()
1696 self._decoder.setstate((b'', dec_flags))
1697 self._snapshot = (dec_flags, b'')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001698
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001699 if chars_to_skip:
1700 # Just like _read_chunk, feed the decoder and save a snapshot.
1701 input_chunk = self.buffer.read(bytes_to_feed)
1702 self._set_decoded_chars(
1703 self._decoder.decode(input_chunk, need_eof))
1704 self._snapshot = (dec_flags, input_chunk)
1705
1706 # Skip chars_to_skip of the decoded characters.
1707 if len(self._decoded_chars) < chars_to_skip:
1708 raise IOError("can't restore logical file position")
1709 self._decoded_chars_used = chars_to_skip
1710
1711 return cookie
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001712
Guido van Rossum024da5c2007-05-17 23:59:11 +00001713 def read(self, n=None):
1714 if n is None:
1715 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001716 decoder = self._decoder or self._get_decoder()
Guido van Rossum78892e42007-04-06 17:31:18 +00001717 if n < 0:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001718 # Read everything.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001719 result = (self._get_decoded_chars() +
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001720 decoder.decode(self.buffer.read(), final=True))
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001721 self._set_decoded_chars('')
1722 self._snapshot = None
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001723 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001724 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001725 # Keep reading chunks until we have n characters to return.
1726 eof = False
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001727 result = self._get_decoded_chars(n)
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001728 while len(result) < n and not eof:
1729 eof = not self._read_chunk()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001730 result += self._get_decoded_chars(n - len(result))
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001731 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001732
Guido van Rossum024da5c2007-05-17 23:59:11 +00001733 def __next__(self):
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001734 self._telling = False
1735 line = self.readline()
1736 if not line:
1737 self._snapshot = None
1738 self._telling = self._seekable
1739 raise StopIteration
1740 return line
1741
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001742 def readline(self, limit=None):
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001743 if self.closed:
1744 raise ValueError("read from closed file")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001745 if limit is None:
1746 limit = -1
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001747
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001748 # Grab all the decoded text (we will rewind any extra bits later).
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001749 line = self._get_decoded_chars()
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001750
Guido van Rossum78892e42007-04-06 17:31:18 +00001751 start = 0
1752 decoder = self._decoder or self._get_decoder()
1753
Guido van Rossum8358db22007-08-18 21:39:55 +00001754 pos = endpos = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001755 while True:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001756 if self._readtranslate:
1757 # Newlines are already translated, only search for \n
1758 pos = line.find('\n', start)
1759 if pos >= 0:
1760 endpos = pos + 1
1761 break
1762 else:
1763 start = len(line)
1764
1765 elif self._readuniversal:
Guido van Rossum8358db22007-08-18 21:39:55 +00001766 # Universal newline search. Find any of \r, \r\n, \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001767 # The decoder ensures that \r\n are not split in two pieces
Guido van Rossum78892e42007-04-06 17:31:18 +00001768
Guido van Rossum8358db22007-08-18 21:39:55 +00001769 # In C we'd look for these in parallel of course.
1770 nlpos = line.find("\n", start)
1771 crpos = line.find("\r", start)
1772 if crpos == -1:
1773 if nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001774 # Nothing found
Guido van Rossum8358db22007-08-18 21:39:55 +00001775 start = len(line)
Guido van Rossum78892e42007-04-06 17:31:18 +00001776 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001777 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001778 endpos = nlpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001779 break
1780 elif nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001781 # Found lone \r
1782 endpos = crpos + 1
1783 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001784 elif nlpos < crpos:
1785 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001786 endpos = nlpos + 1
Guido van Rossum78892e42007-04-06 17:31:18 +00001787 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001788 elif nlpos == crpos + 1:
1789 # Found \r\n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001790 endpos = crpos + 2
Guido van Rossum8358db22007-08-18 21:39:55 +00001791 break
1792 else:
1793 # Found \r
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001794 endpos = crpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001795 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001796 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001797 # non-universal
1798 pos = line.find(self._readnl)
1799 if pos >= 0:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001800 endpos = pos + len(self._readnl)
Guido van Rossum8358db22007-08-18 21:39:55 +00001801 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001802
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001803 if limit >= 0 and len(line) >= limit:
1804 endpos = limit # reached length limit
1805 break
1806
Guido van Rossum78892e42007-04-06 17:31:18 +00001807 # No line ending seen yet - get more data
Guido van Rossum8358db22007-08-18 21:39:55 +00001808 more_line = ''
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001809 while self._read_chunk():
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001810 if self._decoded_chars:
Guido van Rossum78892e42007-04-06 17:31:18 +00001811 break
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001812 if self._decoded_chars:
1813 line += self._get_decoded_chars()
Guido van Rossum8358db22007-08-18 21:39:55 +00001814 else:
1815 # end of file
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001816 self._set_decoded_chars('')
1817 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001818 return line
Guido van Rossum78892e42007-04-06 17:31:18 +00001819
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001820 if limit >= 0 and endpos > limit:
1821 endpos = limit # don't exceed limit
1822
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001823 # Rewind _decoded_chars to just after the line ending we found.
1824 self._rewind_decoded_chars(len(line) - endpos)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001825 return line[:endpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001826
Guido van Rossum8358db22007-08-18 21:39:55 +00001827 @property
1828 def newlines(self):
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001829 return self._decoder.newlines if self._decoder else None
Guido van Rossum024da5c2007-05-17 23:59:11 +00001830
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001831class _StringIO(TextIOWrapper):
1832 """Text I/O implementation using an in-memory buffer.
1833
1834 The initial_value argument sets the value of object. The newline
1835 argument is like the one of TextIOWrapper's constructor.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001836 """
Guido van Rossum024da5c2007-05-17 23:59:11 +00001837
1838 # XXX This is really slow, but fully functional
1839
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001840 def __init__(self, initial_value="", newline="\n"):
1841 super(_StringIO, self).__init__(BytesIO(),
1842 encoding="utf-8",
1843 errors="strict",
1844 newline=newline)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001845 if initial_value:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001846 if not isinstance(initial_value, str):
Guido van Rossum34d19282007-08-09 01:03:29 +00001847 initial_value = str(initial_value)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001848 self.write(initial_value)
1849 self.seek(0)
1850
1851 def getvalue(self):
Guido van Rossum34d19282007-08-09 01:03:29 +00001852 self.flush()
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001853 return self.buffer.getvalue().decode(self._encoding, self._errors)
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001854
1855try:
1856 import _stringio
1857
1858 # This subclass is a reimplementation of the TextIOWrapper
1859 # interface without any of its text decoding facilities. All the
1860 # stored data is manipulated with the efficient
1861 # _stringio._StringIO extension type. Also, the newline decoding
1862 # mechanism of IncrementalNewlineDecoder is reimplemented here for
1863 # efficiency. Doing otherwise, would require us to implement a
1864 # fake decoder which would add an additional and unnecessary layer
1865 # on top of the _StringIO methods.
1866
1867 class StringIO(_stringio._StringIO, TextIOBase):
1868 """Text I/O implementation using an in-memory buffer.
1869
1870 The initial_value argument sets the value of object. The newline
1871 argument is like the one of TextIOWrapper's constructor.
1872 """
1873
1874 _CHUNK_SIZE = 4096
1875
1876 def __init__(self, initial_value="", newline="\n"):
1877 if newline not in (None, "", "\n", "\r", "\r\n"):
1878 raise ValueError("illegal newline value: %r" % (newline,))
1879
1880 self._readuniversal = not newline
1881 self._readtranslate = newline is None
1882 self._readnl = newline
1883 self._writetranslate = newline != ""
1884 self._writenl = newline or os.linesep
1885 self._pending = ""
1886 self._seennl = 0
1887
1888 # Reset the buffer first, in case __init__ is called
1889 # multiple times.
1890 self.truncate(0)
1891 if initial_value is None:
1892 initial_value = ""
1893 self.write(initial_value)
1894 self.seek(0)
1895
1896 @property
1897 def buffer(self):
1898 raise UnsupportedOperation("%s.buffer attribute is unsupported" %
1899 self.__class__.__name__)
1900
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +00001901 # XXX Cruft to support the TextIOWrapper API. This would only
1902 # be meaningful if StringIO supported the buffer attribute.
1903 # Hopefully, a better solution, than adding these pseudo-attributes,
1904 # will be found.
1905 @property
1906 def encoding(self):
1907 return "utf-8"
1908
1909 @property
1910 def errors(self):
1911 return "strict"
1912
1913 @property
1914 def line_buffering(self):
1915 return False
1916
Alexandre Vassalotti794652d2008-06-11 22:58:36 +00001917 def _decode_newlines(self, input, final=False):
1918 # decode input (with the eventual \r from a previous pass)
1919 if self._pending:
1920 input = self._pending + input
1921
1922 # retain last \r even when not translating data:
1923 # then readline() is sure to get \r\n in one pass
1924 if input.endswith("\r") and not final:
1925 input = input[:-1]
1926 self._pending = "\r"
1927 else:
1928 self._pending = ""
1929
1930 # Record which newlines are read
1931 crlf = input.count('\r\n')
1932 cr = input.count('\r') - crlf
1933 lf = input.count('\n') - crlf
1934 self._seennl |= (lf and self._LF) | (cr and self._CR) \
1935 | (crlf and self._CRLF)
1936
1937 if self._readtranslate:
1938 if crlf:
1939 output = input.replace("\r\n", "\n")
1940 if cr:
1941 output = input.replace("\r", "\n")
1942 else:
1943 output = input
1944
1945 return output
1946
1947 def writable(self):
1948 return True
1949
1950 def readable(self):
1951 return True
1952
1953 def seekable(self):
1954 return True
1955
1956 _read = _stringio._StringIO.read
1957 _write = _stringio._StringIO.write
1958 _tell = _stringio._StringIO.tell
1959 _seek = _stringio._StringIO.seek
1960 _truncate = _stringio._StringIO.truncate
1961 _getvalue = _stringio._StringIO.getvalue
1962
1963 def getvalue(self) -> str:
1964 """Retrieve the entire contents of the object."""
1965 if self.closed:
1966 raise ValueError("read on closed file")
1967 return self._getvalue()
1968
1969 def write(self, s: str) -> int:
1970 """Write string s to file.
1971
1972 Returns the number of characters written.
1973 """
1974 if self.closed:
1975 raise ValueError("write to closed file")
1976 if not isinstance(s, str):
1977 raise TypeError("can't write %s to text stream" %
1978 s.__class__.__name__)
1979 length = len(s)
1980 if self._writetranslate and self._writenl != "\n":
1981 s = s.replace("\n", self._writenl)
1982 self._pending = ""
1983 self._write(s)
1984 return length
1985
1986 def read(self, n: int = None) -> str:
1987 """Read at most n characters, returned as a string.
1988
1989 If the argument is negative or omitted, read until EOF
1990 is reached. Return an empty string at EOF.
1991 """
1992 if self.closed:
1993 raise ValueError("read to closed file")
1994 if n is None:
1995 n = -1
1996 res = self._pending
1997 if n < 0:
1998 res += self._decode_newlines(self._read(), True)
1999 self._pending = ""
2000 return res
2001 else:
2002 res = self._decode_newlines(self._read(n), True)
2003 self._pending = res[n:]
2004 return res[:n]
2005
2006 def tell(self) -> int:
2007 """Tell the current file position."""
2008 if self.closed:
2009 raise ValueError("tell from closed file")
2010 if self._pending:
2011 return self._tell() - len(self._pending)
2012 else:
2013 return self._tell()
2014
2015 def seek(self, pos: int = None, whence: int = 0) -> int:
2016 """Change stream position.
2017
2018 Seek to character offset pos relative to position indicated by whence:
2019 0 Start of stream (the default). pos should be >= 0;
2020 1 Current position - pos must be 0;
2021 2 End of stream - pos must be 0.
2022 Returns the new absolute position.
2023 """
2024 if self.closed:
2025 raise ValueError("seek from closed file")
2026 self._pending = ""
2027 return self._seek(pos, whence)
2028
2029 def truncate(self, pos: int = None) -> int:
2030 """Truncate size to pos.
2031
2032 The pos argument defaults to the current file position, as
2033 returned by tell(). Imply an absolute seek to pos.
2034 Returns the new absolute position.
2035 """
2036 if self.closed:
2037 raise ValueError("truncate from closed file")
2038 self._pending = ""
2039 return self._truncate(pos)
2040
2041 def readline(self, limit: int = None) -> str:
2042 if self.closed:
2043 raise ValueError("read from closed file")
2044 if limit is None:
2045 limit = -1
2046 if limit >= 0:
2047 # XXX: Hack to support limit argument, for backwards
2048 # XXX compatibility
2049 line = self.readline()
2050 if len(line) <= limit:
2051 return line
2052 line, self._pending = line[:limit], line[limit:] + self._pending
2053 return line
2054
2055 line = self._pending
2056 self._pending = ""
2057
2058 start = 0
2059 pos = endpos = None
2060 while True:
2061 if self._readtranslate:
2062 # Newlines are already translated, only search for \n
2063 pos = line.find('\n', start)
2064 if pos >= 0:
2065 endpos = pos + 1
2066 break
2067 else:
2068 start = len(line)
2069
2070 elif self._readuniversal:
2071 # Universal newline search. Find any of \r, \r\n, \n
2072 # The decoder ensures that \r\n are not split in two pieces
2073
2074 # In C we'd look for these in parallel of course.
2075 nlpos = line.find("\n", start)
2076 crpos = line.find("\r", start)
2077 if crpos == -1:
2078 if nlpos == -1:
2079 # Nothing found
2080 start = len(line)
2081 else:
2082 # Found \n
2083 endpos = nlpos + 1
2084 break
2085 elif nlpos == -1:
2086 # Found lone \r
2087 endpos = crpos + 1
2088 break
2089 elif nlpos < crpos:
2090 # Found \n
2091 endpos = nlpos + 1
2092 break
2093 elif nlpos == crpos + 1:
2094 # Found \r\n
2095 endpos = crpos + 2
2096 break
2097 else:
2098 # Found \r
2099 endpos = crpos + 1
2100 break
2101 else:
2102 # non-universal
2103 pos = line.find(self._readnl)
2104 if pos >= 0:
2105 endpos = pos + len(self._readnl)
2106 break
2107
2108 # No line ending seen yet - get more data
2109 more_line = self.read(self._CHUNK_SIZE)
2110 if more_line:
2111 line += more_line
2112 else:
2113 # end of file
2114 return line
2115
2116 self._pending = line[endpos:]
2117 return line[:endpos]
2118
2119 _LF = 1
2120 _CR = 2
2121 _CRLF = 4
2122
2123 @property
2124 def newlines(self):
2125 return (None,
2126 "\n",
2127 "\r",
2128 ("\r", "\n"),
2129 "\r\n",
2130 ("\n", "\r\n"),
2131 ("\r", "\r\n"),
2132 ("\r", "\n", "\r\n")
2133 )[self._seennl]
2134
2135
2136except ImportError:
2137 StringIO = _StringIO