blob: a308ac4300b7d8932e2db051b303b88a6913ddff [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
Guido van Rossum78892e42007-04-06 17:31:18 +000063import warnings
Guido van Rossum28524c72007-02-27 05:47:44 +000064
Guido van Rossum5abbf752007-08-27 17:39:33 +000065# open() uses st_blksize whenever we can
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000066DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
Guido van Rossum01a27522007-03-07 01:00:12 +000067
68
Guido van Rossum141f7672007-04-10 00:22:16 +000069class BlockingIOError(IOError):
Guido van Rossum78892e42007-04-06 17:31:18 +000070
Guido van Rossum141f7672007-04-10 00:22:16 +000071 """Exception raised when I/O would block on a non-blocking I/O stream."""
72
73 def __init__(self, errno, strerror, characters_written=0):
Guido van Rossum01a27522007-03-07 01:00:12 +000074 IOError.__init__(self, errno, strerror)
75 self.characters_written = characters_written
76
Guido van Rossum68bbcd22007-02-27 17:19:33 +000077
Guido van Rossume7fc50f2007-12-03 22:54:21 +000078def open(file, mode="r", buffering=None, encoding=None, errors=None,
79 newline=None, closefd=True):
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +000080 r"""Open file and return a stream. If the file cannot be opened, an
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000081 IOError is raised.
Guido van Rossum17e43e52007-02-27 15:45:13 +000082
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000083 file is either a string giving the name (and the path if the file
84 isn't in the current working directory) of the file to be opened or an
85 integer file descriptor of the file to be wrapped. (If a file
86 descriptor is given, it is closed when the returned I/O object is
87 closed, unless closefd is set to False.)
Guido van Rossum8358db22007-08-18 21:39:55 +000088
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000089 mode is an optional string that specifies the mode in which the file
90 is opened. It defaults to 'r' which means open for reading in text
91 mode. Other common values are 'w' for writing (truncating the file if
92 it already exists), and 'a' for appending (which on some Unix systems,
93 means that all writes append to the end of the file regardless of the
94 current seek position). In text mode, if encoding is not specified the
95 encoding used is platform dependent. (For reading and writing raw
96 bytes use binary mode and leave encoding unspecified.) The available
97 modes are:
Guido van Rossum8358db22007-08-18 21:39:55 +000098
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000099 ========= ===============================================================
100 Character Meaning
101 --------- ---------------------------------------------------------------
102 'r' open for reading (default)
103 'w' open for writing, truncating the file first
104 'a' open for writing, appending to the end of the file if it exists
105 'b' binary mode
106 't' text mode (default)
107 '+' open a disk file for updating (reading and writing)
108 'U' universal newline mode (for backwards compatibility; unneeded
109 for new code)
110 ========= ===============================================================
Guido van Rossum17e43e52007-02-27 15:45:13 +0000111
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000112 The default mode is 'rt' (open for reading text). For binary random
113 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
114 'r+b' opens the file without truncation.
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000115
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000116 Python distinguishes between files opened in binary and text modes,
117 even when the underlying operating system doesn't. Files opened in
118 binary mode (appending 'b' to the mode argument) return contents as
119 bytes objects without any decoding. In text mode (the default, or when
120 't' is appended to the mode argument), the contents of the file are
121 returned as strings, the bytes having been first decoded using a
122 platform-dependent encoding or using the specified encoding if given.
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000123
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000124 buffering is an optional integer used to set the buffering policy. By
125 default full buffering is on. Pass 0 to switch buffering off (only
126 allowed in binary mode), 1 to set line buffering, and an integer > 1
127 for full buffering.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000128
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000129 encoding is the name of the encoding used to decode or encode the
130 file. This should only be used in text mode. The default encoding is
131 platform dependent, but any encoding supported by Python can be
132 passed. See the codecs module for the list of supported encodings.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000133
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000134 errors is an optional string that specifies how encoding errors are to
135 be handled---this argument should not be used in binary mode. Pass
136 'strict' to raise a ValueError exception if there is an encoding error
137 (the default of None has the same effect), or pass 'ignore' to ignore
138 errors. (Note that ignoring encoding errors can lead to data loss.)
139 See the documentation for codecs.register for a list of the permitted
140 encoding error strings.
141
142 newline controls how universal newlines works (it only applies to text
143 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
144 follows:
145
146 * On input, if newline is None, universal newlines mode is
147 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
148 these are translated into '\n' before being returned to the
149 caller. If it is '', universal newline mode is enabled, but line
150 endings are returned to the caller untranslated. If it has any of
151 the other legal values, input lines are only terminated by the given
152 string, and the line ending is returned to the caller untranslated.
153
154 * On output, if newline is None, any '\n' characters written are
155 translated to the system default line separator, os.linesep. If
156 newline is '', no translation takes place. If newline is any of the
157 other legal values, any '\n' characters written are translated to
158 the given string.
159
160 If closefd is False, the underlying file descriptor will be kept open
161 when the file is closed. This does not work when a file name is given
162 and must be True in that case.
163
164 open() returns a file object whose type depends on the mode, and
165 through which the standard file operations such as reading and writing
166 are performed. When open() is used to open a file in a text mode ('w',
167 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
168 a file in a binary mode, the returned class varies: in read binary
169 mode, it returns a BufferedReader; in write binary and append binary
170 modes, it returns a BufferedWriter, and in read/write mode, it returns
171 a BufferedRandom.
172
173 It is also possible to use a string or bytearray as a file for both
174 reading and writing. For strings StringIO can be used like a file
175 opened in a text mode, and for bytes a BytesIO can be used like a file
176 opened in a binary mode.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000177 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000178 if not isinstance(file, (str, int)):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000179 raise TypeError("invalid file: %r" % file)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000180 if not isinstance(mode, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000181 raise TypeError("invalid mode: %r" % mode)
182 if buffering is not None and not isinstance(buffering, int):
183 raise TypeError("invalid buffering: %r" % buffering)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000184 if encoding is not None and not isinstance(encoding, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000185 raise TypeError("invalid encoding: %r" % encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000186 if errors is not None and not isinstance(errors, str):
187 raise TypeError("invalid errors: %r" % errors)
Guido van Rossum28524c72007-02-27 05:47:44 +0000188 modes = set(mode)
Guido van Rossum9be55972007-04-07 02:59:27 +0000189 if modes - set("arwb+tU") or len(mode) > len(modes):
Guido van Rossum28524c72007-02-27 05:47:44 +0000190 raise ValueError("invalid mode: %r" % mode)
191 reading = "r" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000192 writing = "w" in modes
Guido van Rossum28524c72007-02-27 05:47:44 +0000193 appending = "a" in modes
194 updating = "+" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000195 text = "t" in modes
196 binary = "b" in modes
Guido van Rossum7165cb12007-07-10 06:54:34 +0000197 if "U" in modes:
198 if writing or appending:
199 raise ValueError("can't use U and writing mode at once")
Guido van Rossum9be55972007-04-07 02:59:27 +0000200 reading = True
Guido van Rossum28524c72007-02-27 05:47:44 +0000201 if text and binary:
202 raise ValueError("can't have text and binary mode at once")
203 if reading + writing + appending > 1:
204 raise ValueError("can't have read/write/append mode at once")
205 if not (reading or writing or appending):
206 raise ValueError("must have exactly one of read/write/append mode")
207 if binary and encoding is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +0000208 raise ValueError("binary mode doesn't take an encoding argument")
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000209 if binary and errors is not None:
210 raise ValueError("binary mode doesn't take an errors argument")
Guido van Rossum9b76da62007-04-11 01:09:03 +0000211 if binary and newline is not None:
212 raise ValueError("binary mode doesn't take a newline argument")
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000213 raw = FileIO(file,
Guido van Rossum28524c72007-02-27 05:47:44 +0000214 (reading and "r" or "") +
215 (writing and "w" or "") +
216 (appending and "a" or "") +
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000217 (updating and "+" or ""),
218 closefd)
Guido van Rossum28524c72007-02-27 05:47:44 +0000219 if buffering is None:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000220 buffering = -1
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000221 line_buffering = False
222 if buffering == 1 or buffering < 0 and raw.isatty():
223 buffering = -1
224 line_buffering = True
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000225 if buffering < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000226 buffering = DEFAULT_BUFFER_SIZE
Guido van Rossum17e43e52007-02-27 15:45:13 +0000227 try:
228 bs = os.fstat(raw.fileno()).st_blksize
229 except (os.error, AttributeError):
Guido van Rossumbb09b212007-03-18 03:36:28 +0000230 pass
231 else:
Guido van Rossum17e43e52007-02-27 15:45:13 +0000232 if bs > 1:
233 buffering = bs
Guido van Rossum28524c72007-02-27 05:47:44 +0000234 if buffering < 0:
235 raise ValueError("invalid buffering size")
236 if buffering == 0:
237 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000238 raw._name = file
239 raw._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000240 return raw
241 raise ValueError("can't have unbuffered text I/O")
242 if updating:
243 buffer = BufferedRandom(raw, buffering)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000244 elif writing or appending:
Guido van Rossum28524c72007-02-27 05:47:44 +0000245 buffer = BufferedWriter(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000246 elif reading:
Guido van Rossum28524c72007-02-27 05:47:44 +0000247 buffer = BufferedReader(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000248 else:
249 raise ValueError("unknown mode: %r" % mode)
Guido van Rossum28524c72007-02-27 05:47:44 +0000250 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000251 buffer.name = file
252 buffer.mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000253 return buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000254 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000255 text.name = file
256 text.mode = mode
257 return text
Guido van Rossum28524c72007-02-27 05:47:44 +0000258
Christian Heimesa33eb062007-12-08 17:47:40 +0000259class _DocDescriptor:
260 """Helper for builtins.open.__doc__
261 """
262 def __get__(self, obj, typ):
263 return (
264 "open(file, mode='r', buffering=None, encoding=None, "
265 "errors=None, newline=None, closefd=True)\n\n" +
266 open.__doc__)
Guido van Rossum28524c72007-02-27 05:47:44 +0000267
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000268class OpenWrapper:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000269 """Wrapper for builtins.open
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000270
271 Trick so that open won't become a bound method when stored
272 as a class variable (as dumbdbm does).
273
274 See initstdio() in Python/pythonrun.c.
275 """
Christian Heimesa33eb062007-12-08 17:47:40 +0000276 __doc__ = _DocDescriptor()
277
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000278 def __new__(cls, *args, **kwargs):
279 return open(*args, **kwargs)
280
281
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000282class UnsupportedOperation(ValueError, IOError):
283 pass
284
285
Guido van Rossumb7f136e2007-08-22 18:14:10 +0000286class IOBase(metaclass=abc.ABCMeta):
Guido van Rossum28524c72007-02-27 05:47:44 +0000287
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000288 """The abstract base class for all I/O classes, acting on streams of
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000289 bytes. There is no public constructor.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000290
Guido van Rossum141f7672007-04-10 00:22:16 +0000291 This class provides dummy implementations for many methods that
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000292 derived classes can override selectively; the default implementations
293 represent a file that cannot be read, written or seeked.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000294
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000295 Even though IOBase does not declare read, readinto, or write because
296 their signatures will vary, implementations and clients should
297 consider those methods part of the interface. Also, implementations
298 may raise a IOError when operations they do not support are called.
Guido van Rossum53807da2007-04-10 19:01:47 +0000299
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000300 The basic type used for binary data read from or written to a file is
301 bytes. bytearrays are accepted too, and in some cases (such as
302 readinto) needed. Text I/O classes work with str data.
303
304 Note that calling any method (even inquiries) on a closed stream is
Benjamin Peterson9a89e962008-04-06 16:47:13 +0000305 undefined. Implementations may raise IOError in this case.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000306
307 IOBase (and its subclasses) support the iterator protocol, meaning
308 that an IOBase object can be iterated over yielding the lines in a
309 stream.
310
311 IOBase also supports the :keyword:`with` statement. In this example,
312 fp is closed after the suite of the with statment is complete:
313
314 with open('spam.txt', 'r') as fp:
315 fp.write('Spam and eggs!')
Guido van Rossum17e43e52007-02-27 15:45:13 +0000316 """
317
Guido van Rossum141f7672007-04-10 00:22:16 +0000318 ### Internal ###
319
320 def _unsupported(self, name: str) -> IOError:
321 """Internal: raise an exception for unsupported operations."""
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000322 raise UnsupportedOperation("%s.%s() not supported" %
323 (self.__class__.__name__, name))
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000324
Guido van Rossum141f7672007-04-10 00:22:16 +0000325 ### Positioning ###
326
Guido van Rossum53807da2007-04-10 19:01:47 +0000327 def seek(self, pos: int, whence: int = 0) -> int:
328 """seek(pos: int, whence: int = 0) -> int. Change stream position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000329
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000330 Change the stream position to byte offset offset. offset is
331 interpreted relative to the position indicated by whence. Values
332 for whence are:
333
334 * 0 -- start of stream (the default); offset should be zero or positive
335 * 1 -- current stream position; offset may be negative
336 * 2 -- end of stream; offset is usually negative
337
338 Return the new absolute position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000339 """
340 self._unsupported("seek")
341
342 def tell(self) -> int:
343 """tell() -> int. Return current stream position."""
Guido van Rossum53807da2007-04-10 19:01:47 +0000344 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000345
Guido van Rossum87429772007-04-10 21:06:59 +0000346 def truncate(self, pos: int = None) -> int:
Georg Brandlf91197c2008-04-09 07:33:01 +0000347 """truncate(pos: int = None) -> int. Truncate file to pos bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000348
Georg Brandlf91197c2008-04-09 07:33:01 +0000349 Pos defaults to the current IO position as reported by tell().
Guido van Rossum87429772007-04-10 21:06:59 +0000350 Returns the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000351 """
352 self._unsupported("truncate")
353
354 ### Flush and close ###
355
356 def flush(self) -> None:
357 """flush() -> None. Flushes write buffers, if applicable.
358
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000359 This is not implemented for read-only and non-blocking streams.
Guido van Rossum141f7672007-04-10 00:22:16 +0000360 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000361 # XXX Should this return the number of bytes written???
Guido van Rossum141f7672007-04-10 00:22:16 +0000362
363 __closed = False
364
365 def close(self) -> None:
366 """close() -> None. Flushes and closes the IO object.
367
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000368 This method has no effect if the file is already closed.
Guido van Rossum141f7672007-04-10 00:22:16 +0000369 """
370 if not self.__closed:
Guido van Rossum469734b2007-07-10 12:00:45 +0000371 try:
372 self.flush()
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000373 except IOError:
374 pass # If flush() fails, just give up
375 self.__closed = True
Guido van Rossum141f7672007-04-10 00:22:16 +0000376
377 def __del__(self) -> None:
378 """Destructor. Calls close()."""
379 # The try/except block is in case this is called at program
380 # exit time, when it's possible that globals have already been
381 # deleted, and then the close() call might fail. Since
382 # there's nothing we can do about such failures and they annoy
383 # the end users, we suppress the traceback.
384 try:
385 self.close()
386 except:
387 pass
388
389 ### Inquiries ###
390
391 def seekable(self) -> bool:
392 """seekable() -> bool. Return whether object supports random access.
393
394 If False, seek(), tell() and truncate() will raise IOError.
395 This method may need to do a test seek().
396 """
397 return False
398
Guido van Rossum5abbf752007-08-27 17:39:33 +0000399 def _checkSeekable(self, msg=None):
400 """Internal: raise an IOError if file is not seekable
401 """
402 if not self.seekable():
403 raise IOError("File or stream is not seekable."
404 if msg is None else msg)
405
406
Guido van Rossum141f7672007-04-10 00:22:16 +0000407 def readable(self) -> bool:
408 """readable() -> bool. Return whether object was opened for reading.
409
410 If False, read() will raise IOError.
411 """
412 return False
413
Guido van Rossum5abbf752007-08-27 17:39:33 +0000414 def _checkReadable(self, msg=None):
415 """Internal: raise an IOError if file is not readable
416 """
417 if not self.readable():
418 raise IOError("File or stream is not readable."
419 if msg is None else msg)
420
Guido van Rossum141f7672007-04-10 00:22:16 +0000421 def writable(self) -> bool:
422 """writable() -> bool. Return whether object was opened for writing.
423
424 If False, write() and truncate() will raise IOError.
425 """
426 return False
427
Guido van Rossum5abbf752007-08-27 17:39:33 +0000428 def _checkWritable(self, msg=None):
429 """Internal: raise an IOError if file is not writable
430 """
431 if not self.writable():
432 raise IOError("File or stream is not writable."
433 if msg is None else msg)
434
Guido van Rossum141f7672007-04-10 00:22:16 +0000435 @property
436 def closed(self):
437 """closed: bool. True iff the file has been closed.
438
439 For backwards compatibility, this is a property, not a predicate.
440 """
441 return self.__closed
442
Guido van Rossum5abbf752007-08-27 17:39:33 +0000443 def _checkClosed(self, msg=None):
444 """Internal: raise an ValueError if file is closed
445 """
446 if self.closed:
447 raise ValueError("I/O operation on closed file."
448 if msg is None else msg)
449
Guido van Rossum141f7672007-04-10 00:22:16 +0000450 ### Context manager ###
451
452 def __enter__(self) -> "IOBase": # That's a forward reference
453 """Context management protocol. Returns self."""
Christian Heimes3ecfea712008-02-09 20:51:34 +0000454 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000455 return self
456
457 def __exit__(self, *args) -> None:
458 """Context management protocol. Calls close()"""
459 self.close()
460
461 ### Lower-level APIs ###
462
463 # XXX Should these be present even if unimplemented?
464
465 def fileno(self) -> int:
466 """fileno() -> int. Returns underlying file descriptor if one exists.
467
468 Raises IOError if the IO object does not use a file descriptor.
469 """
470 self._unsupported("fileno")
471
472 def isatty(self) -> bool:
473 """isatty() -> int. Returns whether this is an 'interactive' stream.
Guido van Rossum141f7672007-04-10 00:22:16 +0000474 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000475 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000476 return False
477
Guido van Rossum7165cb12007-07-10 06:54:34 +0000478 ### Readline[s] and writelines ###
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000479
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000480 def readline(self, limit: int = -1) -> bytes:
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000481 r"""readline(limit: int = -1) -> bytes Read and return a line from the
482 stream.
483
484 If limit is specified, at most limit bytes will be read.
485
486 The line terminator is always b'\n' for binary files; for text
487 files, the newlines argument to open can be used to select the line
488 terminator(s) recognized.
489 """
490 # For backwards compatibility, a (slowish) readline().
Guido van Rossum2bf71382007-06-08 00:07:57 +0000491 if hasattr(self, "peek"):
492 def nreadahead():
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000493 readahead = self.peek(1)
Guido van Rossum2bf71382007-06-08 00:07:57 +0000494 if not readahead:
495 return 1
496 n = (readahead.find(b"\n") + 1) or len(readahead)
497 if limit >= 0:
498 n = min(n, limit)
499 return n
500 else:
501 def nreadahead():
502 return 1
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000503 if limit is None:
504 limit = -1
Guido van Rossum254348e2007-11-21 19:29:53 +0000505 res = bytearray()
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000506 while limit < 0 or len(res) < limit:
Guido van Rossum2bf71382007-06-08 00:07:57 +0000507 b = self.read(nreadahead())
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000508 if not b:
509 break
510 res += b
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000511 if res.endswith(b"\n"):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000512 break
Guido van Rossum98297ee2007-11-06 21:34:58 +0000513 return bytes(res)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000514
Guido van Rossum7165cb12007-07-10 06:54:34 +0000515 def __iter__(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000516 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000517 return self
518
519 def __next__(self):
520 line = self.readline()
521 if not line:
522 raise StopIteration
523 return line
524
525 def readlines(self, hint=None):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000526 """readlines(hint=None) -> list Return a list of lines from the stream.
527
528 hint can be specified to control the number of lines read: no more
529 lines will be read if the total size (in bytes/characters) of all
530 lines so far exceeds hint.
531 """
Guido van Rossum7165cb12007-07-10 06:54:34 +0000532 if hint is None:
533 return list(self)
534 n = 0
535 lines = []
536 for line in self:
537 lines.append(line)
538 n += len(line)
539 if n >= hint:
540 break
541 return lines
542
543 def writelines(self, lines):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000544 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000545 for line in lines:
546 self.write(line)
547
Guido van Rossum141f7672007-04-10 00:22:16 +0000548
549class RawIOBase(IOBase):
550
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000551 """Base class for raw binary I/O."""
Guido van Rossum141f7672007-04-10 00:22:16 +0000552
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000553 # The read() method is implemented by calling readinto(); derived
554 # classes that want to support read() only need to implement
555 # readinto() as a primitive operation. In general, readinto() can be
556 # more efficient than read().
Guido van Rossum141f7672007-04-10 00:22:16 +0000557
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000558 # (It would be tempting to also provide an implementation of
559 # readinto() in terms of read(), in case the latter is a more suitable
560 # primitive operation, but that would lead to nasty recursion in case
561 # a subclass doesn't implement either.)
Guido van Rossum141f7672007-04-10 00:22:16 +0000562
Guido van Rossum7165cb12007-07-10 06:54:34 +0000563 def read(self, n: int = -1) -> bytes:
Guido van Rossum78892e42007-04-06 17:31:18 +0000564 """read(n: int) -> bytes. Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000565
Georg Brandlf91197c2008-04-09 07:33:01 +0000566 Returns an empty bytes object on EOF, or None if the object is
Guido van Rossum01a27522007-03-07 01:00:12 +0000567 set not to block and has no data to read.
568 """
Guido van Rossum7165cb12007-07-10 06:54:34 +0000569 if n is None:
570 n = -1
571 if n < 0:
572 return self.readall()
Guido van Rossum254348e2007-11-21 19:29:53 +0000573 b = bytearray(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000574 n = self.readinto(b)
575 del b[n:]
Guido van Rossum98297ee2007-11-06 21:34:58 +0000576 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000577
Guido van Rossum7165cb12007-07-10 06:54:34 +0000578 def readall(self):
Georg Brandlf91197c2008-04-09 07:33:01 +0000579 """readall() -> bytes. Read until EOF, using multiple read() calls."""
Guido van Rossum254348e2007-11-21 19:29:53 +0000580 res = bytearray()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000581 while True:
582 data = self.read(DEFAULT_BUFFER_SIZE)
583 if not data:
584 break
585 res += data
Guido van Rossum98297ee2007-11-06 21:34:58 +0000586 return bytes(res)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000587
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000588 def readinto(self, b: bytearray) -> int:
589 """readinto(b: bytearray) -> int. Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000590
591 Returns number of bytes read (0 for EOF), or None if the object
592 is set not to block as has no data to read.
593 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000594 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000595
Guido van Rossum141f7672007-04-10 00:22:16 +0000596 def write(self, b: bytes) -> int:
Guido van Rossum78892e42007-04-06 17:31:18 +0000597 """write(b: bytes) -> int. Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000598
Guido van Rossum78892e42007-04-06 17:31:18 +0000599 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000600 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000601 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000602
Guido van Rossum78892e42007-04-06 17:31:18 +0000603
Guido van Rossum141f7672007-04-10 00:22:16 +0000604class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000605
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000606 """Raw I/O implementation for OS files."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000607
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000608 # This multiply inherits from _FileIO and RawIOBase to make
609 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
610 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
611 # to do since _fileio.c is written in C).
Guido van Rossuma9e20242007-03-08 00:43:48 +0000612
Guido van Rossum87429772007-04-10 21:06:59 +0000613 def close(self):
614 _fileio._FileIO.close(self)
615 RawIOBase.close(self)
616
Guido van Rossum13633bb2007-04-13 18:42:35 +0000617 @property
618 def name(self):
619 return self._name
620
Georg Brandlf91197c2008-04-09 07:33:01 +0000621 # XXX(gb): _FileIO already has a mode property
Guido van Rossum13633bb2007-04-13 18:42:35 +0000622 @property
623 def mode(self):
624 return self._mode
625
Guido van Rossuma9e20242007-03-08 00:43:48 +0000626
Guido van Rossumcce92b22007-04-10 14:41:39 +0000627class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000628
629 """Base class for buffered IO objects.
630
631 The main difference with RawIOBase is that the read() method
632 supports omitting the size argument, and does not have a default
633 implementation that defers to readinto().
634
635 In addition, read(), readinto() and write() may raise
636 BlockingIOError if the underlying raw stream is in non-blocking
637 mode and not ready; unlike their raw counterparts, they will never
638 return None.
639
640 A typical implementation should not inherit from a RawIOBase
641 implementation, but wrap one.
642 """
643
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000644 def read(self, n: int = None) -> bytes:
645 """read(n: int = None) -> bytes. Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000646
Guido van Rossum024da5c2007-05-17 23:59:11 +0000647 If the argument is omitted, None, or negative, reads and
648 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000649
650 If the argument is positive, and the underlying raw stream is
651 not 'interactive', multiple raw reads may be issued to satisfy
652 the byte count (unless EOF is reached first). But for
653 interactive raw streams (XXX and for pipes?), at most one raw
654 read will be issued, and a short result does not imply that
655 EOF is imminent.
656
657 Returns an empty bytes array on EOF.
658
659 Raises BlockingIOError if the underlying raw stream has no
660 data at the moment.
661 """
662 self._unsupported("read")
663
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000664 def readinto(self, b: bytearray) -> int:
665 """readinto(b: bytearray) -> int. Read up to len(b) bytes into b.
Guido van Rossum141f7672007-04-10 00:22:16 +0000666
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000667 Like read(), this may issue multiple reads to the underlying raw
668 stream, unless the latter is 'interactive'.
Guido van Rossum141f7672007-04-10 00:22:16 +0000669
670 Returns the number of bytes read (0 for EOF).
671
672 Raises BlockingIOError if the underlying raw stream has no
673 data at the moment.
674 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000675 # XXX This ought to work with anything that supports the buffer API
Guido van Rossum87429772007-04-10 21:06:59 +0000676 data = self.read(len(b))
677 n = len(data)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000678 try:
679 b[:n] = data
680 except TypeError as err:
681 import array
682 if not isinstance(b, array.array):
683 raise err
684 b[:n] = array.array('b', data)
Guido van Rossum87429772007-04-10 21:06:59 +0000685 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000686
687 def write(self, b: bytes) -> int:
688 """write(b: bytes) -> int. Write the given buffer to the IO stream.
689
690 Returns the number of bytes written, which is never less than
691 len(b).
692
693 Raises BlockingIOError if the buffer is full and the
694 underlying raw stream cannot accept more data at the moment.
695 """
696 self._unsupported("write")
697
698
699class _BufferedIOMixin(BufferedIOBase):
700
701 """A mixin implementation of BufferedIOBase with an underlying raw stream.
702
703 This passes most requests on to the underlying raw stream. It
704 does *not* provide implementations of read(), readinto() or
705 write().
706 """
707
708 def __init__(self, raw):
709 self.raw = raw
710
711 ### Positioning ###
712
713 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000714 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000715
716 def tell(self):
717 return self.raw.tell()
718
719 def truncate(self, pos=None):
Guido van Rossum79b79ee2007-10-25 23:21:03 +0000720 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
721 # and a flush may be necessary to synch both views of the current
722 # file state.
723 self.flush()
Guido van Rossum57233cb2007-10-26 17:19:33 +0000724
725 if pos is None:
726 pos = self.tell()
727 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000728
729 ### Flush and close ###
730
731 def flush(self):
732 self.raw.flush()
733
734 def close(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000735 if not self.closed:
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000736 try:
737 self.flush()
738 except IOError:
739 pass # If flush() fails, just give up
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000740 self.raw.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000741
742 ### Inquiries ###
743
744 def seekable(self):
745 return self.raw.seekable()
746
747 def readable(self):
748 return self.raw.readable()
749
750 def writable(self):
751 return self.raw.writable()
752
753 @property
754 def closed(self):
755 return self.raw.closed
756
757 ### Lower-level APIs ###
758
759 def fileno(self):
760 return self.raw.fileno()
761
762 def isatty(self):
763 return self.raw.isatty()
764
765
Guido van Rossum024da5c2007-05-17 23:59:11 +0000766class BytesIO(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000767
Guido van Rossum024da5c2007-05-17 23:59:11 +0000768 """Buffered I/O implementation using an in-memory bytes buffer."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000769
Guido van Rossum024da5c2007-05-17 23:59:11 +0000770 def __init__(self, initial_bytes=None):
Guido van Rossum254348e2007-11-21 19:29:53 +0000771 buf = bytearray()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000772 if initial_bytes is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000773 buf += initial_bytes
774 self._buffer = buf
Guido van Rossum28524c72007-02-27 05:47:44 +0000775 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000776
777 def getvalue(self):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000778 """getvalue() -> bytes Return the bytes value (contents) of the buffer
779 """
Guido van Rossum98297ee2007-11-06 21:34:58 +0000780 return bytes(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000781
Guido van Rossum024da5c2007-05-17 23:59:11 +0000782 def read(self, n=None):
783 if n is None:
784 n = -1
Guido van Rossum141f7672007-04-10 00:22:16 +0000785 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000786 n = len(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000787 newpos = min(len(self._buffer), self._pos + n)
788 b = self._buffer[self._pos : newpos]
789 self._pos = newpos
Guido van Rossum98297ee2007-11-06 21:34:58 +0000790 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000791
Guido van Rossum024da5c2007-05-17 23:59:11 +0000792 def read1(self, n):
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000793 """This is the same as read.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000794 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000795 return self.read(n)
796
Guido van Rossum28524c72007-02-27 05:47:44 +0000797 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000798 if self.closed:
799 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +0000800 if isinstance(b, str):
801 raise TypeError("can't write str to binary stream")
Guido van Rossum28524c72007-02-27 05:47:44 +0000802 n = len(b)
803 newpos = self._pos + n
Guido van Rossumb972a782007-07-21 00:25:15 +0000804 if newpos > len(self._buffer):
805 # Inserts null bytes between the current end of the file
806 # and the new write position.
Guido van Rossuma74184e2007-08-29 04:05:57 +0000807 padding = b'\x00' * (newpos - len(self._buffer) - n)
Guido van Rossumb972a782007-07-21 00:25:15 +0000808 self._buffer[self._pos:newpos - n] = padding
Guido van Rossum28524c72007-02-27 05:47:44 +0000809 self._buffer[self._pos:newpos] = b
810 self._pos = newpos
811 return n
812
813 def seek(self, pos, whence=0):
Christian Heimes3ab4f652007-11-09 01:27:29 +0000814 try:
815 pos = pos.__index__()
816 except AttributeError as err:
817 raise TypeError("an integer is required") from err
Guido van Rossum28524c72007-02-27 05:47:44 +0000818 if whence == 0:
819 self._pos = max(0, pos)
820 elif whence == 1:
821 self._pos = max(0, self._pos + pos)
822 elif whence == 2:
823 self._pos = max(0, len(self._buffer) + pos)
824 else:
825 raise IOError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000826 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000827
828 def tell(self):
829 return self._pos
830
831 def truncate(self, pos=None):
832 if pos is None:
833 pos = self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000834 del self._buffer[pos:]
Guido van Rossum87429772007-04-10 21:06:59 +0000835 return pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000836
837 def readable(self):
838 return True
839
840 def writable(self):
841 return True
842
843 def seekable(self):
844 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000845
846
Guido van Rossum141f7672007-04-10 00:22:16 +0000847class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000848
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000849 """BufferedReader(raw[, buffer_size])
850
851 A buffer for a readable, sequential BaseRawIO object.
852
853 The constructor creates a BufferedReader for the given readable raw
854 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
855 is used.
856 """
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000857
Guido van Rossum78892e42007-04-06 17:31:18 +0000858 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000859 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000860 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000861 raw._checkReadable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000862 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum01a27522007-03-07 01:00:12 +0000863 self._read_buf = b""
Guido van Rossum78892e42007-04-06 17:31:18 +0000864 self.buffer_size = buffer_size
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000865
Guido van Rossum024da5c2007-05-17 23:59:11 +0000866 def read(self, n=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000867 """Read n bytes.
868
869 Returns exactly n bytes of data unless the underlying raw IO
Walter Dörwalda3270002007-05-29 19:13:29 +0000870 stream reaches EOF or if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000871 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000872 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000873 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000874 if n is None:
875 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +0000876 nodata_val = b""
Guido van Rossum141f7672007-04-10 00:22:16 +0000877 while n < 0 or len(self._read_buf) < n:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000878 to_read = max(self.buffer_size,
879 n if n is not None else 2*len(self._read_buf))
Guido van Rossum78892e42007-04-06 17:31:18 +0000880 current = self.raw.read(to_read)
Guido van Rossum78892e42007-04-06 17:31:18 +0000881 if current in (b"", None):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000882 nodata_val = current
883 break
Guido van Rossum01a27522007-03-07 01:00:12 +0000884 self._read_buf += current
885 if self._read_buf:
Guido van Rossum141f7672007-04-10 00:22:16 +0000886 if n < 0:
Guido van Rossum01a27522007-03-07 01:00:12 +0000887 n = len(self._read_buf)
888 out = self._read_buf[:n]
889 self._read_buf = self._read_buf[n:]
890 else:
891 out = nodata_val
892 return out
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000893
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000894 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000895 """Returns buffered bytes without advancing the position.
896
897 The argument indicates a desired minimal number of bytes; we
898 do at most one raw read to satisfy it. We never return more
899 than self.buffer_size.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000900 """
901 want = min(n, self.buffer_size)
902 have = len(self._read_buf)
903 if have < want:
904 to_read = self.buffer_size - have
905 current = self.raw.read(to_read)
906 if current:
907 self._read_buf += current
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000908 return self._read_buf
Guido van Rossum13633bb2007-04-13 18:42:35 +0000909
910 def read1(self, n):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000911 """Reads up to n bytes, with at most one read() system call."""
912 # Returns up to n bytes. If at least one byte is buffered, we
913 # only return buffered bytes. Otherwise, we do one raw read.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000914 if n <= 0:
915 return b""
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000916 self.peek(1)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000917 return self.read(min(n, len(self._read_buf)))
918
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000919 def tell(self):
920 return self.raw.tell() - len(self._read_buf)
921
922 def seek(self, pos, whence=0):
923 if whence == 1:
924 pos -= len(self._read_buf)
Guido van Rossum53807da2007-04-10 19:01:47 +0000925 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000926 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +0000927 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000928
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000929
Guido van Rossum141f7672007-04-10 00:22:16 +0000930class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000931
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000932 """BufferedWriter(raw[, buffer_size[, max_buffer_size]])
933
934 A buffer for a writeable sequential RawIO object.
935
936 The constructor creates a BufferedWriter for the given writeable raw
937 stream. If the buffer_size is not given, it defaults to
938 DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
939 twice the buffer size.
940 """
Guido van Rossum78892e42007-04-06 17:31:18 +0000941
Guido van Rossum141f7672007-04-10 00:22:16 +0000942 def __init__(self, raw,
943 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000944 raw._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000945 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000946 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +0000947 self.max_buffer_size = (2*buffer_size
948 if max_buffer_size is None
949 else max_buffer_size)
Guido van Rossum254348e2007-11-21 19:29:53 +0000950 self._write_buf = bytearray()
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000951
952 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000953 if self.closed:
954 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +0000955 if isinstance(b, str):
956 raise TypeError("can't write str to binary stream")
Guido van Rossum01a27522007-03-07 01:00:12 +0000957 # XXX we can implement some more tricks to try and avoid partial writes
Guido van Rossum01a27522007-03-07 01:00:12 +0000958 if len(self._write_buf) > self.buffer_size:
959 # We're full, so let's pre-flush the buffer
960 try:
961 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000962 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000963 # We can't accept anything else.
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000964 # XXX Why not just let the exception pass through?
Guido van Rossum141f7672007-04-10 00:22:16 +0000965 raise BlockingIOError(e.errno, e.strerror, 0)
Guido van Rossumd4103952007-04-12 05:44:49 +0000966 before = len(self._write_buf)
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000967 self._write_buf.extend(b)
Guido van Rossumd4103952007-04-12 05:44:49 +0000968 written = len(self._write_buf) - before
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000969 if len(self._write_buf) > self.buffer_size:
Guido van Rossum01a27522007-03-07 01:00:12 +0000970 try:
971 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000972 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000973 if (len(self._write_buf) > self.max_buffer_size):
974 # We've hit max_buffer_size. We have to accept a partial
975 # write and cut back our buffer.
976 overage = len(self._write_buf) - self.max_buffer_size
977 self._write_buf = self._write_buf[:self.max_buffer_size]
Guido van Rossum141f7672007-04-10 00:22:16 +0000978 raise BlockingIOError(e.errno, e.strerror, overage)
Guido van Rossumd4103952007-04-12 05:44:49 +0000979 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000980
981 def flush(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000982 if self.closed:
983 raise ValueError("flush of closed file")
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000984 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +0000985 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000986 while self._write_buf:
987 n = self.raw.write(self._write_buf)
988 del self._write_buf[:n]
989 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000990 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000991 n = e.characters_written
992 del self._write_buf[:n]
993 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000994 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000995
996 def tell(self):
997 return self.raw.tell() + len(self._write_buf)
998
999 def seek(self, pos, whence=0):
1000 self.flush()
Guido van Rossum53807da2007-04-10 19:01:47 +00001001 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001002
Guido van Rossum01a27522007-03-07 01:00:12 +00001003
Guido van Rossum141f7672007-04-10 00:22:16 +00001004class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001005
Guido van Rossum01a27522007-03-07 01:00:12 +00001006 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001007
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001008 A buffered reader object and buffered writer object put together to
1009 form a sequential IO object that can read and write. This is typically
1010 used with a socket or two-way pipe.
Guido van Rossum78892e42007-04-06 17:31:18 +00001011
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001012 reader and writer are RawIOBase objects that are readable and
1013 writeable respectively. If the buffer_size is omitted it defaults to
1014 DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
1015 defaults to twice the buffer size.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001016 """
1017
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001018 # XXX The usefulness of this (compared to having two separate IO
1019 # objects) is questionable.
1020
Guido van Rossum141f7672007-04-10 00:22:16 +00001021 def __init__(self, reader, writer,
1022 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1023 """Constructor.
1024
1025 The arguments are two RawIO instances.
1026 """
Guido van Rossum5abbf752007-08-27 17:39:33 +00001027 reader._checkReadable()
1028 writer._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001029 self.reader = BufferedReader(reader, buffer_size)
1030 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001031
Guido van Rossum024da5c2007-05-17 23:59:11 +00001032 def read(self, n=None):
1033 if n is None:
1034 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001035 return self.reader.read(n)
1036
Guido van Rossum141f7672007-04-10 00:22:16 +00001037 def readinto(self, b):
1038 return self.reader.readinto(b)
1039
Guido van Rossum01a27522007-03-07 01:00:12 +00001040 def write(self, b):
1041 return self.writer.write(b)
1042
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001043 def peek(self, n=0):
1044 return self.reader.peek(n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001045
1046 def read1(self, n):
1047 return self.reader.read1(n)
1048
Guido van Rossum01a27522007-03-07 01:00:12 +00001049 def readable(self):
1050 return self.reader.readable()
1051
1052 def writable(self):
1053 return self.writer.writable()
1054
1055 def flush(self):
1056 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001057
Guido van Rossum01a27522007-03-07 01:00:12 +00001058 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +00001059 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +00001060 self.reader.close()
1061
1062 def isatty(self):
1063 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +00001064
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001065 @property
1066 def closed(self):
Guido van Rossum141f7672007-04-10 00:22:16 +00001067 return self.writer.closed()
Guido van Rossum01a27522007-03-07 01:00:12 +00001068
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001069
Guido van Rossum141f7672007-04-10 00:22:16 +00001070class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +00001071
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001072 """BufferedRandom(raw[, buffer_size[, max_buffer_size]])
1073
1074 A buffered interface to random access streams.
1075
1076 The constructor creates a reader and writer for a seekable stream,
1077 raw, given in the first argument. If the buffer_size is omitted it
1078 defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
1079 writer) defaults to twice the buffer size.
1080 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001081
Guido van Rossum141f7672007-04-10 00:22:16 +00001082 def __init__(self, raw,
1083 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001084 raw._checkSeekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001085 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001086 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1087
Guido van Rossum01a27522007-03-07 01:00:12 +00001088 def seek(self, pos, whence=0):
1089 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001090 # First do the raw seek, then empty the read buffer, so that
1091 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +00001092 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001093 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +00001094 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +00001095
1096 def tell(self):
1097 if (self._write_buf):
1098 return self.raw.tell() + len(self._write_buf)
1099 else:
1100 return self.raw.tell() - len(self._read_buf)
1101
Guido van Rossum024da5c2007-05-17 23:59:11 +00001102 def read(self, n=None):
1103 if n is None:
1104 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001105 self.flush()
1106 return BufferedReader.read(self, n)
1107
Guido van Rossum141f7672007-04-10 00:22:16 +00001108 def readinto(self, b):
1109 self.flush()
1110 return BufferedReader.readinto(self, b)
1111
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001112 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +00001113 self.flush()
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001114 return BufferedReader.peek(self, n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001115
1116 def read1(self, n):
1117 self.flush()
1118 return BufferedReader.read1(self, n)
1119
Guido van Rossum01a27522007-03-07 01:00:12 +00001120 def write(self, b):
Guido van Rossum78892e42007-04-06 17:31:18 +00001121 if self._read_buf:
1122 self.raw.seek(-len(self._read_buf), 1) # Undo readahead
1123 self._read_buf = b""
Guido van Rossum01a27522007-03-07 01:00:12 +00001124 return BufferedWriter.write(self, b)
1125
Guido van Rossum78892e42007-04-06 17:31:18 +00001126
Guido van Rossumcce92b22007-04-10 14:41:39 +00001127class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +00001128
1129 """Base class for text I/O.
1130
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001131 This class provides a character and line based interface to stream
1132 I/O. There is no readinto method because Python's character strings
1133 are immutable. There is no public constructor.
Guido van Rossum78892e42007-04-06 17:31:18 +00001134 """
1135
1136 def read(self, n: int = -1) -> str:
1137 """read(n: int = -1) -> str. Read at most n characters from stream.
1138
1139 Read from underlying buffer until we have n characters or we hit EOF.
1140 If n is negative or omitted, read until EOF.
1141 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001142 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +00001143
Guido van Rossum9b76da62007-04-11 01:09:03 +00001144 def write(self, s: str) -> int:
1145 """write(s: str) -> int. Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001146 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +00001147
Guido van Rossum9b76da62007-04-11 01:09:03 +00001148 def truncate(self, pos: int = None) -> int:
1149 """truncate(pos: int = None) -> int. Truncate size to pos."""
1150 self.flush()
1151 if pos is None:
1152 pos = self.tell()
1153 self.seek(pos)
1154 return self.buffer.truncate()
1155
Guido van Rossum78892e42007-04-06 17:31:18 +00001156 def readline(self) -> str:
1157 """readline() -> str. Read until newline or EOF.
1158
1159 Returns an empty string if EOF is hit immediately.
1160 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001161 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +00001162
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001163 @property
1164 def encoding(self):
1165 """Subclasses should override."""
1166 return None
1167
Guido van Rossum8358db22007-08-18 21:39:55 +00001168 @property
1169 def newlines(self):
1170 """newlines -> None | str | tuple of str. Line endings translated
1171 so far.
1172
1173 Only line endings translated during reading are considered.
1174
1175 Subclasses should override.
1176 """
1177 return None
1178
Guido van Rossum78892e42007-04-06 17:31:18 +00001179
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001180class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001181 r"""Codec used when reading a file in universal newlines mode. It wraps
1182 another incremental decoder, translating \r\n and \r into \n. It also
1183 records the types of newlines encountered. When used with
1184 translate=False, it ensures that the newline sequence is returned in
1185 one piece.
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001186 """
1187 def __init__(self, decoder, translate, errors='strict'):
1188 codecs.IncrementalDecoder.__init__(self, errors=errors)
1189 self.buffer = b''
1190 self.translate = translate
1191 self.decoder = decoder
1192 self.seennl = 0
1193
1194 def decode(self, input, final=False):
1195 # decode input (with the eventual \r from a previous pass)
1196 if self.buffer:
1197 input = self.buffer + input
1198
1199 output = self.decoder.decode(input, final=final)
1200
1201 # retain last \r even when not translating data:
1202 # then readline() is sure to get \r\n in one pass
1203 if output.endswith("\r") and not final:
1204 output = output[:-1]
1205 self.buffer = b'\r'
1206 else:
1207 self.buffer = b''
1208
1209 # Record which newlines are read
1210 crlf = output.count('\r\n')
1211 cr = output.count('\r') - crlf
1212 lf = output.count('\n') - crlf
1213 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1214 | (crlf and self._CRLF)
1215
1216 if self.translate:
1217 if crlf:
1218 output = output.replace("\r\n", "\n")
1219 if cr:
1220 output = output.replace("\r", "\n")
1221
1222 return output
1223
1224 def getstate(self):
1225 buf, flag = self.decoder.getstate()
1226 return buf + self.buffer, flag
1227
1228 def setstate(self, state):
1229 buf, flag = state
1230 if buf.endswith(b'\r'):
1231 self.buffer = b'\r'
1232 buf = buf[:-1]
1233 else:
1234 self.buffer = b''
1235 self.decoder.setstate((buf, flag))
1236
1237 def reset(self):
Alexandre Vassalottic3d7fe02007-12-28 01:24:22 +00001238 self.seennl = 0
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001239 self.buffer = b''
1240 self.decoder.reset()
1241
1242 _LF = 1
1243 _CR = 2
1244 _CRLF = 4
1245
1246 @property
1247 def newlines(self):
1248 return (None,
1249 "\n",
1250 "\r",
1251 ("\r", "\n"),
1252 "\r\n",
1253 ("\n", "\r\n"),
1254 ("\r", "\r\n"),
1255 ("\r", "\n", "\r\n")
1256 )[self.seennl]
1257
1258
Guido van Rossum78892e42007-04-06 17:31:18 +00001259class TextIOWrapper(TextIOBase):
1260
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001261 r"""TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
Guido van Rossum78892e42007-04-06 17:31:18 +00001262
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001263 Character and line based layer over a BufferedIOBase object, buffer.
1264
1265 encoding gives the name of the encoding that the stream will be
1266 decoded or encoded with. It defaults to locale.getpreferredencoding.
1267
1268 errors determines the strictness of encoding and decoding (see the
1269 codecs.register) and defaults to "strict".
1270
1271 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1272 handling of line endings. If it is None, universal newlines is
1273 enabled. With this enabled, on input, the lines endings '\n', '\r',
1274 or '\r\n' are translated to '\n' before being returned to the
1275 caller. Conversely, on output, '\n' is translated to the system
1276 default line seperator, os.linesep. If newline is any other of its
1277 legal values, that newline becomes the newline when the file is read
1278 and it is returned untranslated. On output, '\n' is converted to the
1279 newline.
1280
1281 If line_buffering is True, a call to flush is implied when a call to
1282 write contains a newline character.
Guido van Rossum78892e42007-04-06 17:31:18 +00001283 """
1284
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001285 _CHUNK_SIZE = 128
Guido van Rossum78892e42007-04-06 17:31:18 +00001286
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001287 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1288 line_buffering=False):
Guido van Rossum8358db22007-08-18 21:39:55 +00001289 if newline not in (None, "", "\n", "\r", "\r\n"):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001290 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +00001291 if encoding is None:
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001292 try:
1293 encoding = os.device_encoding(buffer.fileno())
Brett Cannon041683d2007-10-11 23:08:53 +00001294 except (AttributeError, UnsupportedOperation):
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001295 pass
1296 if encoding is None:
Martin v. Löwisd78d3b42007-08-11 15:36:45 +00001297 try:
1298 import locale
1299 except ImportError:
1300 # Importing locale may fail if Python is being built
1301 encoding = "ascii"
1302 else:
1303 encoding = locale.getpreferredencoding()
Guido van Rossum78892e42007-04-06 17:31:18 +00001304
Christian Heimes8bd14fb2007-11-08 16:34:32 +00001305 if not isinstance(encoding, str):
1306 raise ValueError("invalid encoding: %r" % encoding)
1307
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001308 if errors is None:
1309 errors = "strict"
1310 else:
1311 if not isinstance(errors, str):
1312 raise ValueError("invalid errors: %r" % errors)
1313
Guido van Rossum78892e42007-04-06 17:31:18 +00001314 self.buffer = buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001315 self._line_buffering = line_buffering
Guido van Rossum78892e42007-04-06 17:31:18 +00001316 self._encoding = encoding
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001317 self._errors = errors
Guido van Rossum8358db22007-08-18 21:39:55 +00001318 self._readuniversal = not newline
1319 self._readtranslate = newline is None
1320 self._readnl = newline
1321 self._writetranslate = newline != ''
1322 self._writenl = newline or os.linesep
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001323 self._encoder = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001324 self._decoder = None
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001325 self._decoded_chars = '' # buffer for text returned from decoder
1326 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001327 self._snapshot = None # info for reconstructing decoder state
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001328 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001329
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001330 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1331 # where dec_flags is the second (integer) item of the decoder state
1332 # and next_input is the chunk of input bytes that comes next after the
1333 # snapshot point. We use this to reconstruct decoder states in tell().
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001334
1335 # Naming convention:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001336 # - "bytes_..." for integer variables that count input bytes
1337 # - "chars_..." for integer variables that count decoded characters
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001338
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001339 @property
1340 def encoding(self):
1341 return self._encoding
1342
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001343 @property
1344 def errors(self):
1345 return self._errors
1346
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001347 @property
1348 def line_buffering(self):
1349 return self._line_buffering
1350
Ka-Ping Yeeddaa7062008-03-17 20:35:15 +00001351 def seekable(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001352 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +00001353
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001354 def flush(self):
1355 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001356 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001357
1358 def close(self):
Guido van Rossum33e7a8e2007-07-22 20:38:07 +00001359 try:
1360 self.flush()
1361 except:
1362 pass # If flush() fails, just give up
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001363 self.buffer.close()
1364
1365 @property
1366 def closed(self):
1367 return self.buffer.closed
1368
Guido van Rossum9be55972007-04-07 02:59:27 +00001369 def fileno(self):
1370 return self.buffer.fileno()
1371
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001372 def isatty(self):
1373 return self.buffer.isatty()
1374
Guido van Rossum78892e42007-04-06 17:31:18 +00001375 def write(self, s: str):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001376 if self.closed:
1377 raise ValueError("write to closed file")
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001378 if not isinstance(s, str):
Guido van Rossumdcce8392007-08-29 18:10:08 +00001379 raise TypeError("can't write %s to text stream" %
1380 s.__class__.__name__)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001381 length = len(s)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001382 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
Guido van Rossum8358db22007-08-18 21:39:55 +00001383 if haslf and self._writetranslate and self._writenl != "\n":
1384 s = s.replace("\n", self._writenl)
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001385 encoder = self._encoder or self._get_encoder()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001386 # XXX What if we were just reading?
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001387 b = encoder.encode(s)
Guido van Rossum8358db22007-08-18 21:39:55 +00001388 self.buffer.write(b)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001389 if self._line_buffering and (haslf or "\r" in s):
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001390 self.flush()
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001391 self._snapshot = None
1392 if self._decoder:
1393 self._decoder.reset()
1394 return length
Guido van Rossum78892e42007-04-06 17:31:18 +00001395
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001396 def _get_encoder(self):
1397 make_encoder = codecs.getincrementalencoder(self._encoding)
1398 self._encoder = make_encoder(self._errors)
1399 return self._encoder
1400
Guido van Rossum78892e42007-04-06 17:31:18 +00001401 def _get_decoder(self):
1402 make_decoder = codecs.getincrementaldecoder(self._encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001403 decoder = make_decoder(self._errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001404 if self._readuniversal:
1405 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1406 self._decoder = decoder
Guido van Rossum78892e42007-04-06 17:31:18 +00001407 return decoder
1408
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001409 # The following three methods implement an ADT for _decoded_chars.
1410 # Text returned from the decoder is buffered here until the client
1411 # requests it by calling our read() or readline() method.
1412 def _set_decoded_chars(self, chars):
1413 """Set the _decoded_chars buffer."""
1414 self._decoded_chars = chars
1415 self._decoded_chars_used = 0
1416
1417 def _get_decoded_chars(self, n=None):
1418 """Advance into the _decoded_chars buffer."""
1419 offset = self._decoded_chars_used
1420 if n is None:
1421 chars = self._decoded_chars[offset:]
1422 else:
1423 chars = self._decoded_chars[offset:offset + n]
1424 self._decoded_chars_used += len(chars)
1425 return chars
1426
1427 def _rewind_decoded_chars(self, n):
1428 """Rewind the _decoded_chars buffer."""
1429 if self._decoded_chars_used < n:
1430 raise AssertionError("rewind decoded_chars out of bounds")
1431 self._decoded_chars_used -= n
1432
Guido van Rossum9b76da62007-04-11 01:09:03 +00001433 def _read_chunk(self):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001434 """
1435 Read and decode the next chunk of data from the BufferedReader.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001436 """
1437
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001438 # The return value is True unless EOF was reached. The decoded
1439 # string is placed in self._decoded_chars (replacing its previous
1440 # value). The entire input chunk is sent to the decoder, though
1441 # some of it may remain buffered in the decoder, yet to be
1442 # converted.
1443
Guido van Rossum5abbf752007-08-27 17:39:33 +00001444 if self._decoder is None:
1445 raise ValueError("no decoder")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001446
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001447 if self._telling:
1448 # To prepare for tell(), we need to snapshot a point in the
1449 # file where the decoder's input buffer is empty.
Guido van Rossum9b76da62007-04-11 01:09:03 +00001450
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001451 dec_buffer, dec_flags = self._decoder.getstate()
1452 # Given this, we know there was a valid snapshot point
1453 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001454
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001455 # Read a chunk, decode it, and put the result in self._decoded_chars.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001456 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1457 eof = not input_chunk
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001458 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001459
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001460 if self._telling:
1461 # At the snapshot point, len(dec_buffer) bytes before the read,
1462 # the next input to be decoded is dec_buffer + input_chunk.
1463 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1464
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001465 return not eof
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001466
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001467 def _pack_cookie(self, position, dec_flags=0,
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001468 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001469 # The meaning of a tell() cookie is: seek to position, set the
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001470 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001471 # into the decoder with need_eof as the EOF flag, then skip
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001472 # chars_to_skip characters of the decoded result. For most simple
1473 # decoders, tell() will often just give a byte offset in the file.
1474 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1475 (chars_to_skip<<192) | bool(need_eof)<<256)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001476
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001477 def _unpack_cookie(self, bigint):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001478 rest, position = divmod(bigint, 1<<64)
1479 rest, dec_flags = divmod(rest, 1<<64)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001480 rest, bytes_to_feed = divmod(rest, 1<<64)
1481 need_eof, chars_to_skip = divmod(rest, 1<<64)
1482 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
Guido van Rossum9b76da62007-04-11 01:09:03 +00001483
1484 def tell(self):
1485 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001486 raise IOError("underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001487 if not self._telling:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001488 raise IOError("telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001489 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001490 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001491 decoder = self._decoder
1492 if decoder is None or self._snapshot is None:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001493 if self._decoded_chars:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001494 # This should never happen.
1495 raise AssertionError("pending decoded text")
Guido van Rossumcba608c2007-04-11 14:19:59 +00001496 return position
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001497
1498 # Skip backward to the snapshot point (see _read_chunk).
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001499 dec_flags, next_input = self._snapshot
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001500 position -= len(next_input)
1501
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001502 # How many decoded characters have been used up since the snapshot?
1503 chars_to_skip = self._decoded_chars_used
1504 if chars_to_skip == 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001505 # We haven't moved from the snapshot point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001506 return self._pack_cookie(position, dec_flags)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001507
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001508 # Starting from the snapshot position, we will walk the decoder
1509 # forward until it gives us enough decoded characters.
Guido van Rossumd76e7792007-04-17 02:38:04 +00001510 saved_state = decoder.getstate()
1511 try:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001512 # Note our initial start point.
1513 decoder.setstate((b'', dec_flags))
1514 start_pos = position
1515 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001516 need_eof = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001517
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001518 # Feed the decoder one byte at a time. As we go, note the
1519 # nearest "safe start point" before the current location
1520 # (a point where the decoder has nothing buffered, so seek()
1521 # can safely start from there and advance to this location).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001522 next_byte = bytearray(1)
1523 for next_byte[0] in next_input:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001524 bytes_fed += 1
1525 chars_decoded += len(decoder.decode(next_byte))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001526 dec_buffer, dec_flags = decoder.getstate()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001527 if not dec_buffer and chars_decoded <= chars_to_skip:
1528 # Decoder buffer is empty, so this is a safe start point.
1529 start_pos += bytes_fed
1530 chars_to_skip -= chars_decoded
1531 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1532 if chars_decoded >= chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001533 break
1534 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001535 # We didn't get enough decoded data; signal EOF to get more.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001536 chars_decoded += len(decoder.decode(b'', final=True))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001537 need_eof = 1
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001538 if chars_decoded < chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001539 raise IOError("can't reconstruct logical file position")
1540
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001541 # The returned cookie corresponds to the last safe start point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001542 return self._pack_cookie(
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001543 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001544 finally:
1545 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001546
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001547 def seek(self, cookie, whence=0):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001548 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001549 raise IOError("underlying stream is not seekable")
1550 if whence == 1: # seek relative to current position
1551 if cookie != 0:
1552 raise IOError("can't do nonzero cur-relative seeks")
1553 # Seeking to the current position should attempt to
1554 # sync the underlying buffer with the current position.
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001555 whence = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001556 cookie = self.tell()
1557 if whence == 2: # seek relative to end of file
1558 if cookie != 0:
1559 raise IOError("can't do nonzero end-relative seeks")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001560 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001561 position = self.buffer.seek(0, 2)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001562 self._set_decoded_chars('')
1563 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001564 if self._decoder:
1565 self._decoder.reset()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001566 return position
Guido van Rossum9b76da62007-04-11 01:09:03 +00001567 if whence != 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001568 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
Guido van Rossum9b76da62007-04-11 01:09:03 +00001569 (whence,))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001570 if cookie < 0:
1571 raise ValueError("negative seek position %r" % (cookie,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001572 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001573
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001574 # The strategy of seek() is to go back to the safe start point
1575 # and replay the effect of read(chars_to_skip) from there.
1576 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001577 self._unpack_cookie(cookie)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001578
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001579 # Seek back to the safe start point.
1580 self.buffer.seek(start_pos)
1581 self._set_decoded_chars('')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001582 self._snapshot = None
1583
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001584 # Restore the decoder to its state from the safe start point.
1585 if self._decoder or dec_flags or chars_to_skip:
1586 self._decoder = self._decoder or self._get_decoder()
1587 self._decoder.setstate((b'', dec_flags))
1588 self._snapshot = (dec_flags, b'')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001589
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001590 if chars_to_skip:
1591 # Just like _read_chunk, feed the decoder and save a snapshot.
1592 input_chunk = self.buffer.read(bytes_to_feed)
1593 self._set_decoded_chars(
1594 self._decoder.decode(input_chunk, need_eof))
1595 self._snapshot = (dec_flags, input_chunk)
1596
1597 # Skip chars_to_skip of the decoded characters.
1598 if len(self._decoded_chars) < chars_to_skip:
1599 raise IOError("can't restore logical file position")
1600 self._decoded_chars_used = chars_to_skip
1601
1602 return cookie
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001603
Guido van Rossum024da5c2007-05-17 23:59:11 +00001604 def read(self, n=None):
1605 if n is None:
1606 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001607 decoder = self._decoder or self._get_decoder()
Guido van Rossum78892e42007-04-06 17:31:18 +00001608 if n < 0:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001609 # Read everything.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001610 result = (self._get_decoded_chars() +
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001611 decoder.decode(self.buffer.read(), final=True))
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001612 self._set_decoded_chars('')
1613 self._snapshot = None
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001614 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001615 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001616 # Keep reading chunks until we have n characters to return.
1617 eof = False
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001618 result = self._get_decoded_chars(n)
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001619 while len(result) < n and not eof:
1620 eof = not self._read_chunk()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001621 result += self._get_decoded_chars(n - len(result))
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001622 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001623
Guido van Rossum024da5c2007-05-17 23:59:11 +00001624 def __next__(self):
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001625 self._telling = False
1626 line = self.readline()
1627 if not line:
1628 self._snapshot = None
1629 self._telling = self._seekable
1630 raise StopIteration
1631 return line
1632
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001633 def readline(self, limit=None):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001634 if limit is None:
1635 limit = -1
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001636
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001637 # Grab all the decoded text (we will rewind any extra bits later).
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001638 line = self._get_decoded_chars()
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001639
Guido van Rossum78892e42007-04-06 17:31:18 +00001640 start = 0
1641 decoder = self._decoder or self._get_decoder()
1642
Guido van Rossum8358db22007-08-18 21:39:55 +00001643 pos = endpos = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001644 while True:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001645 if self._readtranslate:
1646 # Newlines are already translated, only search for \n
1647 pos = line.find('\n', start)
1648 if pos >= 0:
1649 endpos = pos + 1
1650 break
1651 else:
1652 start = len(line)
1653
1654 elif self._readuniversal:
Guido van Rossum8358db22007-08-18 21:39:55 +00001655 # Universal newline search. Find any of \r, \r\n, \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001656 # The decoder ensures that \r\n are not split in two pieces
Guido van Rossum78892e42007-04-06 17:31:18 +00001657
Guido van Rossum8358db22007-08-18 21:39:55 +00001658 # In C we'd look for these in parallel of course.
1659 nlpos = line.find("\n", start)
1660 crpos = line.find("\r", start)
1661 if crpos == -1:
1662 if nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001663 # Nothing found
Guido van Rossum8358db22007-08-18 21:39:55 +00001664 start = len(line)
Guido van Rossum78892e42007-04-06 17:31:18 +00001665 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001666 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001667 endpos = nlpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001668 break
1669 elif nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001670 # Found lone \r
1671 endpos = crpos + 1
1672 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001673 elif nlpos < crpos:
1674 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001675 endpos = nlpos + 1
Guido van Rossum78892e42007-04-06 17:31:18 +00001676 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001677 elif nlpos == crpos + 1:
1678 # Found \r\n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001679 endpos = crpos + 2
Guido van Rossum8358db22007-08-18 21:39:55 +00001680 break
1681 else:
1682 # Found \r
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001683 endpos = crpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001684 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001685 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001686 # non-universal
1687 pos = line.find(self._readnl)
1688 if pos >= 0:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001689 endpos = pos + len(self._readnl)
Guido van Rossum8358db22007-08-18 21:39:55 +00001690 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001691
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001692 if limit >= 0 and len(line) >= limit:
1693 endpos = limit # reached length limit
1694 break
1695
Guido van Rossum78892e42007-04-06 17:31:18 +00001696 # No line ending seen yet - get more data
Guido van Rossum8358db22007-08-18 21:39:55 +00001697 more_line = ''
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001698 while self._read_chunk():
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001699 if self._decoded_chars:
Guido van Rossum78892e42007-04-06 17:31:18 +00001700 break
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001701 if self._decoded_chars:
1702 line += self._get_decoded_chars()
Guido van Rossum8358db22007-08-18 21:39:55 +00001703 else:
1704 # end of file
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001705 self._set_decoded_chars('')
1706 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001707 return line
Guido van Rossum78892e42007-04-06 17:31:18 +00001708
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001709 if limit >= 0 and endpos > limit:
1710 endpos = limit # don't exceed limit
1711
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001712 # Rewind _decoded_chars to just after the line ending we found.
1713 self._rewind_decoded_chars(len(line) - endpos)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001714 return line[:endpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001715
Guido van Rossum8358db22007-08-18 21:39:55 +00001716 @property
1717 def newlines(self):
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001718 return self._decoder.newlines if self._decoder else None
Guido van Rossum024da5c2007-05-17 23:59:11 +00001719
1720class StringIO(TextIOWrapper):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001721 """StringIO([initial_value[, encoding, [errors, [newline]]]])
1722
1723 An in-memory stream for text. The initial_value argument sets the
1724 value of object. The other arguments are like those of TextIOWrapper's
1725 constructor.
1726 """
Guido van Rossum024da5c2007-05-17 23:59:11 +00001727
1728 # XXX This is really slow, but fully functional
1729
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001730 def __init__(self, initial_value="", encoding="utf-8",
1731 errors="strict", newline="\n"):
Guido van Rossum3e1f85e2007-07-27 18:03:11 +00001732 super(StringIO, self).__init__(BytesIO(),
1733 encoding=encoding,
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001734 errors=errors,
Guido van Rossum3e1f85e2007-07-27 18:03:11 +00001735 newline=newline)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001736 if initial_value:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001737 if not isinstance(initial_value, str):
Guido van Rossum34d19282007-08-09 01:03:29 +00001738 initial_value = str(initial_value)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001739 self.write(initial_value)
1740 self.seek(0)
1741
1742 def getvalue(self):
Guido van Rossum34d19282007-08-09 01:03:29 +00001743 self.flush()
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001744 return self.buffer.getvalue().decode(self._encoding, self._errors)