blob: 30b256f1fa47455b8f7e277bc3b8aa4f31c15080 [file] [log] [blame]
Guido van Rossum28524c72007-02-27 05:47:44 +00001"""
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00002The io module provides the Python interfaces to stream handling. The
3builtin open function is defined in this module.
4
5At the top of the I/O hierarchy is the abstract base class IOBase. It
6defines the basic interface to a stream. Note, however, that there is no
7seperation between reading and writing to streams; implementations are
8allowed to throw an IOError if they do not support a given operation.
9
10Extending IOBase is RawIOBase which deals simply with the reading and
11writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
12an interface to OS files.
13
14BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
15subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
16streams that are readable, writable, and both respectively.
17BufferedRandom provides a buffered interface to random access
18streams. BytesIO is a simple stream of in-memory bytes.
19
20Another IOBase subclass, TextIOBase, deals with the encoding and decoding
21of streams into text. TextIOWrapper, which extends it, is a buffered text
22interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
23is a in-memory stream for text.
24
25Argument names are not part of the specification, and only the arguments
26of open() are intended to be used as keyword arguments.
27
28data:
29
30DEFAULT_BUFFER_SIZE
31
32 An int containing the default buffer size used by the module's buffered
33 I/O classes. open() uses the file's blksize (as obtained by os.stat) if
34 possible.
35"""
36# New I/O library conforming to PEP 3116.
37
38# This is a prototype; hopefully eventually some of this will be
39# reimplemented in C.
40
41# XXX edge cases when switching between reading/writing
42# XXX need to support 1 meaning line-buffered
43# XXX whenever an argument is None, use the default value
44# XXX read/write ops should check readable/writable
45# XXX buffered readinto should work with arbitrary buffer objects
46# XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG
47# XXX check writable, readable and seekable in appropriate places
48
Guido van Rossum28524c72007-02-27 05:47:44 +000049
Guido van Rossum68bbcd22007-02-27 17:19:33 +000050__author__ = ("Guido van Rossum <guido@python.org>, "
Guido van Rossum78892e42007-04-06 17:31:18 +000051 "Mike Verdone <mike.verdone@gmail.com>, "
52 "Mark Russell <mark.russell@zen.co.uk>")
Guido van Rossum28524c72007-02-27 05:47:44 +000053
Guido van Rossum141f7672007-04-10 00:22:16 +000054__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
Guido van Rossum5abbf752007-08-27 17:39:33 +000055 "BytesIO", "StringIO", "BufferedIOBase",
Guido van Rossum01a27522007-03-07 01:00:12 +000056 "BufferedReader", "BufferedWriter", "BufferedRWPair",
Guido van Rossum141f7672007-04-10 00:22:16 +000057 "BufferedRandom", "TextIOBase", "TextIOWrapper"]
Guido van Rossum28524c72007-02-27 05:47:44 +000058
59import os
Guido van Rossumb7f136e2007-08-22 18:14:10 +000060import abc
Guido van Rossum78892e42007-04-06 17:31:18 +000061import sys
62import codecs
Guido van Rossum141f7672007-04-10 00:22:16 +000063import _fileio
Guido van Rossum78892e42007-04-06 17:31:18 +000064import warnings
Guido van Rossum28524c72007-02-27 05:47:44 +000065
Guido van Rossum5abbf752007-08-27 17:39:33 +000066# open() uses st_blksize whenever we can
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000067DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
Guido van Rossum01a27522007-03-07 01:00:12 +000068
69
Guido van Rossum141f7672007-04-10 00:22:16 +000070class BlockingIOError(IOError):
Guido van Rossum78892e42007-04-06 17:31:18 +000071
Guido van Rossum141f7672007-04-10 00:22:16 +000072 """Exception raised when I/O would block on a non-blocking I/O stream."""
73
74 def __init__(self, errno, strerror, characters_written=0):
Guido van Rossum01a27522007-03-07 01:00:12 +000075 IOError.__init__(self, errno, strerror)
76 self.characters_written = characters_written
77
Guido van Rossum68bbcd22007-02-27 17:19:33 +000078
Guido van Rossume7fc50f2007-12-03 22:54:21 +000079def open(file, mode="r", buffering=None, encoding=None, errors=None,
80 newline=None, closefd=True):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000081 r"""
82 Open file and return a stream. If the file cannot be opened, an
83 IOError is raised.
Guido van Rossum17e43e52007-02-27 15:45:13 +000084
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000085 file is either a string giving the name (and the path if the file
86 isn't in the current working directory) of the file to be opened or an
87 integer file descriptor of the file to be wrapped. (If a file
88 descriptor is given, it is closed when the returned I/O object is
89 closed, unless closefd is set to False.)
Guido van Rossum8358db22007-08-18 21:39:55 +000090
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000091 mode is an optional string that specifies the mode in which the file
92 is opened. It defaults to 'r' which means open for reading in text
93 mode. Other common values are 'w' for writing (truncating the file if
94 it already exists), and 'a' for appending (which on some Unix systems,
95 means that all writes append to the end of the file regardless of the
96 current seek position). In text mode, if encoding is not specified the
97 encoding used is platform dependent. (For reading and writing raw
98 bytes use binary mode and leave encoding unspecified.) The available
99 modes are:
Guido van Rossum8358db22007-08-18 21:39:55 +0000100
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000101 ========= ===============================================================
102 Character Meaning
103 --------- ---------------------------------------------------------------
104 'r' open for reading (default)
105 'w' open for writing, truncating the file first
106 'a' open for writing, appending to the end of the file if it exists
107 'b' binary mode
108 't' text mode (default)
109 '+' open a disk file for updating (reading and writing)
110 'U' universal newline mode (for backwards compatibility; unneeded
111 for new code)
112 ========= ===============================================================
Guido van Rossum17e43e52007-02-27 15:45:13 +0000113
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000114 The default mode is 'rt' (open for reading text). For binary random
115 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
116 'r+b' opens the file without truncation.
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000117
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000118 Python distinguishes between files opened in binary and text modes,
119 even when the underlying operating system doesn't. Files opened in
120 binary mode (appending 'b' to the mode argument) return contents as
121 bytes objects without any decoding. In text mode (the default, or when
122 't' is appended to the mode argument), the contents of the file are
123 returned as strings, the bytes having been first decoded using a
124 platform-dependent encoding or using the specified encoding if given.
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000125
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000126 buffering is an optional integer used to set the buffering policy. By
127 default full buffering is on. Pass 0 to switch buffering off (only
128 allowed in binary mode), 1 to set line buffering, and an integer > 1
129 for full buffering.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000130
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000131 encoding is the name of the encoding used to decode or encode the
132 file. This should only be used in text mode. The default encoding is
133 platform dependent, but any encoding supported by Python can be
134 passed. See the codecs module for the list of supported encodings.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000135
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000136 errors is an optional string that specifies how encoding errors are to
137 be handled---this argument should not be used in binary mode. Pass
138 'strict' to raise a ValueError exception if there is an encoding error
139 (the default of None has the same effect), or pass 'ignore' to ignore
140 errors. (Note that ignoring encoding errors can lead to data loss.)
141 See the documentation for codecs.register for a list of the permitted
142 encoding error strings.
143
144 newline controls how universal newlines works (it only applies to text
145 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
146 follows:
147
148 * On input, if newline is None, universal newlines mode is
149 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
150 these are translated into '\n' before being returned to the
151 caller. If it is '', universal newline mode is enabled, but line
152 endings are returned to the caller untranslated. If it has any of
153 the other legal values, input lines are only terminated by the given
154 string, and the line ending is returned to the caller untranslated.
155
156 * On output, if newline is None, any '\n' characters written are
157 translated to the system default line separator, os.linesep. If
158 newline is '', no translation takes place. If newline is any of the
159 other legal values, any '\n' characters written are translated to
160 the given string.
161
162 If closefd is False, the underlying file descriptor will be kept open
163 when the file is closed. This does not work when a file name is given
164 and must be True in that case.
165
166 open() returns a file object whose type depends on the mode, and
167 through which the standard file operations such as reading and writing
168 are performed. When open() is used to open a file in a text mode ('w',
169 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
170 a file in a binary mode, the returned class varies: in read binary
171 mode, it returns a BufferedReader; in write binary and append binary
172 modes, it returns a BufferedWriter, and in read/write mode, it returns
173 a BufferedRandom.
174
175 It is also possible to use a string or bytearray as a file for both
176 reading and writing. For strings StringIO can be used like a file
177 opened in a text mode, and for bytes a BytesIO can be used like a file
178 opened in a binary mode.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000179 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000180 if not isinstance(file, (str, int)):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000181 raise TypeError("invalid file: %r" % file)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000182 if not isinstance(mode, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000183 raise TypeError("invalid mode: %r" % mode)
184 if buffering is not None and not isinstance(buffering, int):
185 raise TypeError("invalid buffering: %r" % buffering)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000186 if encoding is not None and not isinstance(encoding, str):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000187 raise TypeError("invalid encoding: %r" % encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000188 if errors is not None and not isinstance(errors, str):
189 raise TypeError("invalid errors: %r" % errors)
Guido van Rossum28524c72007-02-27 05:47:44 +0000190 modes = set(mode)
Guido van Rossum9be55972007-04-07 02:59:27 +0000191 if modes - set("arwb+tU") or len(mode) > len(modes):
Guido van Rossum28524c72007-02-27 05:47:44 +0000192 raise ValueError("invalid mode: %r" % mode)
193 reading = "r" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000194 writing = "w" in modes
Guido van Rossum28524c72007-02-27 05:47:44 +0000195 appending = "a" in modes
196 updating = "+" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000197 text = "t" in modes
198 binary = "b" in modes
Guido van Rossum7165cb12007-07-10 06:54:34 +0000199 if "U" in modes:
200 if writing or appending:
201 raise ValueError("can't use U and writing mode at once")
Guido van Rossum9be55972007-04-07 02:59:27 +0000202 reading = True
Guido van Rossum28524c72007-02-27 05:47:44 +0000203 if text and binary:
204 raise ValueError("can't have text and binary mode at once")
205 if reading + writing + appending > 1:
206 raise ValueError("can't have read/write/append mode at once")
207 if not (reading or writing or appending):
208 raise ValueError("must have exactly one of read/write/append mode")
209 if binary and encoding is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +0000210 raise ValueError("binary mode doesn't take an encoding argument")
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000211 if binary and errors is not None:
212 raise ValueError("binary mode doesn't take an errors argument")
Guido van Rossum9b76da62007-04-11 01:09:03 +0000213 if binary and newline is not None:
214 raise ValueError("binary mode doesn't take a newline argument")
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000215 raw = FileIO(file,
Guido van Rossum28524c72007-02-27 05:47:44 +0000216 (reading and "r" or "") +
217 (writing and "w" or "") +
218 (appending and "a" or "") +
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000219 (updating and "+" or ""),
220 closefd)
Guido van Rossum28524c72007-02-27 05:47:44 +0000221 if buffering is None:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000222 buffering = -1
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000223 line_buffering = False
224 if buffering == 1 or buffering < 0 and raw.isatty():
225 buffering = -1
226 line_buffering = True
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000227 if buffering < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000228 buffering = DEFAULT_BUFFER_SIZE
Guido van Rossum17e43e52007-02-27 15:45:13 +0000229 try:
230 bs = os.fstat(raw.fileno()).st_blksize
231 except (os.error, AttributeError):
Guido van Rossumbb09b212007-03-18 03:36:28 +0000232 pass
233 else:
Guido van Rossum17e43e52007-02-27 15:45:13 +0000234 if bs > 1:
235 buffering = bs
Guido van Rossum28524c72007-02-27 05:47:44 +0000236 if buffering < 0:
237 raise ValueError("invalid buffering size")
238 if buffering == 0:
239 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000240 raw._name = file
241 raw._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000242 return raw
243 raise ValueError("can't have unbuffered text I/O")
244 if updating:
245 buffer = BufferedRandom(raw, buffering)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000246 elif writing or appending:
Guido van Rossum28524c72007-02-27 05:47:44 +0000247 buffer = BufferedWriter(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000248 elif reading:
Guido van Rossum28524c72007-02-27 05:47:44 +0000249 buffer = BufferedReader(raw, buffering)
Guido van Rossum5abbf752007-08-27 17:39:33 +0000250 else:
251 raise ValueError("unknown mode: %r" % mode)
Guido van Rossum28524c72007-02-27 05:47:44 +0000252 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000253 buffer.name = file
254 buffer.mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000255 return buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +0000256 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000257 text.name = file
258 text.mode = mode
259 return text
Guido van Rossum28524c72007-02-27 05:47:44 +0000260
Christian Heimesa33eb062007-12-08 17:47:40 +0000261class _DocDescriptor:
262 """Helper for builtins.open.__doc__
263 """
264 def __get__(self, obj, typ):
265 return (
266 "open(file, mode='r', buffering=None, encoding=None, "
267 "errors=None, newline=None, closefd=True)\n\n" +
268 open.__doc__)
Guido van Rossum28524c72007-02-27 05:47:44 +0000269
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000270class OpenWrapper:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000271 """Wrapper for builtins.open
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000272
273 Trick so that open won't become a bound method when stored
274 as a class variable (as dumbdbm does).
275
276 See initstdio() in Python/pythonrun.c.
277 """
Christian Heimesa33eb062007-12-08 17:47:40 +0000278 __doc__ = _DocDescriptor()
279
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000280 def __new__(cls, *args, **kwargs):
281 return open(*args, **kwargs)
282
283
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000284class UnsupportedOperation(ValueError, IOError):
285 pass
286
287
Guido van Rossumb7f136e2007-08-22 18:14:10 +0000288class IOBase(metaclass=abc.ABCMeta):
Guido van Rossum28524c72007-02-27 05:47:44 +0000289
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000290 """
291 The abstract base class for all I/O classes, acting on streams of
292 bytes. There is no public constructor.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000293
Guido van Rossum141f7672007-04-10 00:22:16 +0000294 This class provides dummy implementations for many methods that
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000295 derived classes can override selectively; the default implementations
296 represent a file that cannot be read, written or seeked.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000297
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000298 Even though IOBase does not declare read, readinto, or write because
299 their signatures will vary, implementations and clients should
300 consider those methods part of the interface. Also, implementations
301 may raise a IOError when operations they do not support are called.
Guido van Rossum53807da2007-04-10 19:01:47 +0000302
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000303 The basic type used for binary data read from or written to a file is
304 bytes. bytearrays are accepted too, and in some cases (such as
305 readinto) needed. Text I/O classes work with str data.
306
307 Note that calling any method (even inquiries) on a closed stream is
Benjamin Peterson9a89e962008-04-06 16:47:13 +0000308 undefined. Implementations may raise IOError in this case.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000309
310 IOBase (and its subclasses) support the iterator protocol, meaning
311 that an IOBase object can be iterated over yielding the lines in a
312 stream.
313
314 IOBase also supports the :keyword:`with` statement. In this example,
315 fp is closed after the suite of the with statment is complete:
316
317 with open('spam.txt', 'r') as fp:
318 fp.write('Spam and eggs!')
Guido van Rossum17e43e52007-02-27 15:45:13 +0000319 """
320
Guido van Rossum141f7672007-04-10 00:22:16 +0000321 ### Internal ###
322
323 def _unsupported(self, name: str) -> IOError:
324 """Internal: raise an exception for unsupported operations."""
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000325 raise UnsupportedOperation("%s.%s() not supported" %
326 (self.__class__.__name__, name))
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000327
Guido van Rossum141f7672007-04-10 00:22:16 +0000328 ### Positioning ###
329
Guido van Rossum53807da2007-04-10 19:01:47 +0000330 def seek(self, pos: int, whence: int = 0) -> int:
331 """seek(pos: int, whence: int = 0) -> int. Change stream position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000332
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000333 Change the stream position to byte offset offset. offset is
334 interpreted relative to the position indicated by whence. Values
335 for whence are:
336
337 * 0 -- start of stream (the default); offset should be zero or positive
338 * 1 -- current stream position; offset may be negative
339 * 2 -- end of stream; offset is usually negative
340
341 Return the new absolute position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000342 """
343 self._unsupported("seek")
344
345 def tell(self) -> int:
346 """tell() -> int. Return current stream position."""
Guido van Rossum53807da2007-04-10 19:01:47 +0000347 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000348
Guido van Rossum87429772007-04-10 21:06:59 +0000349 def truncate(self, pos: int = None) -> int:
Georg Brandlf91197c2008-04-09 07:33:01 +0000350 """truncate(pos: int = None) -> int. Truncate file to pos bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000351
Georg Brandlf91197c2008-04-09 07:33:01 +0000352 Pos defaults to the current IO position as reported by tell().
Guido van Rossum87429772007-04-10 21:06:59 +0000353 Returns the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000354 """
355 self._unsupported("truncate")
356
357 ### Flush and close ###
358
359 def flush(self) -> None:
360 """flush() -> None. Flushes write buffers, if applicable.
361
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000362 This is not implemented for read-only and non-blocking streams.
Guido van Rossum141f7672007-04-10 00:22:16 +0000363 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000364 # XXX Should this return the number of bytes written???
Guido van Rossum141f7672007-04-10 00:22:16 +0000365
366 __closed = False
367
368 def close(self) -> None:
369 """close() -> None. Flushes and closes the IO object.
370
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000371 This method has no effect if the file is already closed.
Guido van Rossum141f7672007-04-10 00:22:16 +0000372 """
373 if not self.__closed:
Guido van Rossum469734b2007-07-10 12:00:45 +0000374 try:
375 self.flush()
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000376 except IOError:
377 pass # If flush() fails, just give up
378 self.__closed = True
Guido van Rossum141f7672007-04-10 00:22:16 +0000379
380 def __del__(self) -> None:
381 """Destructor. Calls close()."""
382 # The try/except block is in case this is called at program
383 # exit time, when it's possible that globals have already been
384 # deleted, and then the close() call might fail. Since
385 # there's nothing we can do about such failures and they annoy
386 # the end users, we suppress the traceback.
387 try:
388 self.close()
389 except:
390 pass
391
392 ### Inquiries ###
393
394 def seekable(self) -> bool:
395 """seekable() -> bool. Return whether object supports random access.
396
397 If False, seek(), tell() and truncate() will raise IOError.
398 This method may need to do a test seek().
399 """
400 return False
401
Guido van Rossum5abbf752007-08-27 17:39:33 +0000402 def _checkSeekable(self, msg=None):
403 """Internal: raise an IOError if file is not seekable
404 """
405 if not self.seekable():
406 raise IOError("File or stream is not seekable."
407 if msg is None else msg)
408
409
Guido van Rossum141f7672007-04-10 00:22:16 +0000410 def readable(self) -> bool:
411 """readable() -> bool. Return whether object was opened for reading.
412
413 If False, read() will raise IOError.
414 """
415 return False
416
Guido van Rossum5abbf752007-08-27 17:39:33 +0000417 def _checkReadable(self, msg=None):
418 """Internal: raise an IOError if file is not readable
419 """
420 if not self.readable():
421 raise IOError("File or stream is not readable."
422 if msg is None else msg)
423
Guido van Rossum141f7672007-04-10 00:22:16 +0000424 def writable(self) -> bool:
425 """writable() -> bool. Return whether object was opened for writing.
426
427 If False, write() and truncate() will raise IOError.
428 """
429 return False
430
Guido van Rossum5abbf752007-08-27 17:39:33 +0000431 def _checkWritable(self, msg=None):
432 """Internal: raise an IOError if file is not writable
433 """
434 if not self.writable():
435 raise IOError("File or stream is not writable."
436 if msg is None else msg)
437
Guido van Rossum141f7672007-04-10 00:22:16 +0000438 @property
439 def closed(self):
440 """closed: bool. True iff the file has been closed.
441
442 For backwards compatibility, this is a property, not a predicate.
443 """
444 return self.__closed
445
Guido van Rossum5abbf752007-08-27 17:39:33 +0000446 def _checkClosed(self, msg=None):
447 """Internal: raise an ValueError if file is closed
448 """
449 if self.closed:
450 raise ValueError("I/O operation on closed file."
451 if msg is None else msg)
452
Guido van Rossum141f7672007-04-10 00:22:16 +0000453 ### Context manager ###
454
455 def __enter__(self) -> "IOBase": # That's a forward reference
456 """Context management protocol. Returns self."""
Christian Heimes3ecfea712008-02-09 20:51:34 +0000457 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000458 return self
459
460 def __exit__(self, *args) -> None:
461 """Context management protocol. Calls close()"""
462 self.close()
463
464 ### Lower-level APIs ###
465
466 # XXX Should these be present even if unimplemented?
467
468 def fileno(self) -> int:
469 """fileno() -> int. Returns underlying file descriptor if one exists.
470
471 Raises IOError if the IO object does not use a file descriptor.
472 """
473 self._unsupported("fileno")
474
475 def isatty(self) -> bool:
476 """isatty() -> int. Returns whether this is an 'interactive' stream.
Guido van Rossum141f7672007-04-10 00:22:16 +0000477 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000478 self._checkClosed()
Guido van Rossum141f7672007-04-10 00:22:16 +0000479 return False
480
Guido van Rossum7165cb12007-07-10 06:54:34 +0000481 ### Readline[s] and writelines ###
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000482
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000483 def readline(self, limit: int = -1) -> bytes:
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000484 r"""readline(limit: int = -1) -> bytes Read and return a line from the
485 stream.
486
487 If limit is specified, at most limit bytes will be read.
488
489 The line terminator is always b'\n' for binary files; for text
490 files, the newlines argument to open can be used to select the line
491 terminator(s) recognized.
492 """
493 # For backwards compatibility, a (slowish) readline().
Guido van Rossum2bf71382007-06-08 00:07:57 +0000494 if hasattr(self, "peek"):
495 def nreadahead():
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000496 readahead = self.peek(1)
Guido van Rossum2bf71382007-06-08 00:07:57 +0000497 if not readahead:
498 return 1
499 n = (readahead.find(b"\n") + 1) or len(readahead)
500 if limit >= 0:
501 n = min(n, limit)
502 return n
503 else:
504 def nreadahead():
505 return 1
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000506 if limit is None:
507 limit = -1
Guido van Rossum254348e2007-11-21 19:29:53 +0000508 res = bytearray()
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000509 while limit < 0 or len(res) < limit:
Guido van Rossum2bf71382007-06-08 00:07:57 +0000510 b = self.read(nreadahead())
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000511 if not b:
512 break
513 res += b
Guido van Rossum48fc58a2007-06-07 23:45:37 +0000514 if res.endswith(b"\n"):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000515 break
Guido van Rossum98297ee2007-11-06 21:34:58 +0000516 return bytes(res)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000517
Guido van Rossum7165cb12007-07-10 06:54:34 +0000518 def __iter__(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000519 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000520 return self
521
522 def __next__(self):
523 line = self.readline()
524 if not line:
525 raise StopIteration
526 return line
527
528 def readlines(self, hint=None):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000529 """readlines(hint=None) -> list Return a list of lines from the stream.
530
531 hint can be specified to control the number of lines read: no more
532 lines will be read if the total size (in bytes/characters) of all
533 lines so far exceeds hint.
534 """
Guido van Rossum7165cb12007-07-10 06:54:34 +0000535 if hint is None:
536 return list(self)
537 n = 0
538 lines = []
539 for line in self:
540 lines.append(line)
541 n += len(line)
542 if n >= hint:
543 break
544 return lines
545
546 def writelines(self, lines):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000547 self._checkClosed()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000548 for line in lines:
549 self.write(line)
550
Guido van Rossum141f7672007-04-10 00:22:16 +0000551
552class RawIOBase(IOBase):
553
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000554 """Base class for raw binary I/O."""
Guido van Rossum141f7672007-04-10 00:22:16 +0000555
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000556 # The read() method is implemented by calling readinto(); derived
557 # classes that want to support read() only need to implement
558 # readinto() as a primitive operation. In general, readinto() can be
559 # more efficient than read().
Guido van Rossum141f7672007-04-10 00:22:16 +0000560
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000561 # (It would be tempting to also provide an implementation of
562 # readinto() in terms of read(), in case the latter is a more suitable
563 # primitive operation, but that would lead to nasty recursion in case
564 # a subclass doesn't implement either.)
Guido van Rossum141f7672007-04-10 00:22:16 +0000565
Guido van Rossum7165cb12007-07-10 06:54:34 +0000566 def read(self, n: int = -1) -> bytes:
Guido van Rossum78892e42007-04-06 17:31:18 +0000567 """read(n: int) -> bytes. Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000568
Georg Brandlf91197c2008-04-09 07:33:01 +0000569 Returns an empty bytes object on EOF, or None if the object is
Guido van Rossum01a27522007-03-07 01:00:12 +0000570 set not to block and has no data to read.
571 """
Guido van Rossum7165cb12007-07-10 06:54:34 +0000572 if n is None:
573 n = -1
574 if n < 0:
575 return self.readall()
Guido van Rossum254348e2007-11-21 19:29:53 +0000576 b = bytearray(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000577 n = self.readinto(b)
578 del b[n:]
Guido van Rossum98297ee2007-11-06 21:34:58 +0000579 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000580
Guido van Rossum7165cb12007-07-10 06:54:34 +0000581 def readall(self):
Georg Brandlf91197c2008-04-09 07:33:01 +0000582 """readall() -> bytes. Read until EOF, using multiple read() calls."""
Guido van Rossum254348e2007-11-21 19:29:53 +0000583 res = bytearray()
Guido van Rossum7165cb12007-07-10 06:54:34 +0000584 while True:
585 data = self.read(DEFAULT_BUFFER_SIZE)
586 if not data:
587 break
588 res += data
Guido van Rossum98297ee2007-11-06 21:34:58 +0000589 return bytes(res)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000590
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000591 def readinto(self, b: bytearray) -> int:
592 """readinto(b: bytearray) -> int. Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000593
594 Returns number of bytes read (0 for EOF), or None if the object
595 is set not to block as has no data to read.
596 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000597 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000598
Guido van Rossum141f7672007-04-10 00:22:16 +0000599 def write(self, b: bytes) -> int:
Guido van Rossum78892e42007-04-06 17:31:18 +0000600 """write(b: bytes) -> int. Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000601
Guido van Rossum78892e42007-04-06 17:31:18 +0000602 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000603 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000604 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000605
Guido van Rossum78892e42007-04-06 17:31:18 +0000606
Guido van Rossum141f7672007-04-10 00:22:16 +0000607class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000608
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000609 """Raw I/O implementation for OS files."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000610
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000611 # This multiply inherits from _FileIO and RawIOBase to make
612 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
613 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
614 # to do since _fileio.c is written in C).
Guido van Rossuma9e20242007-03-08 00:43:48 +0000615
Guido van Rossum87429772007-04-10 21:06:59 +0000616 def close(self):
617 _fileio._FileIO.close(self)
618 RawIOBase.close(self)
619
Guido van Rossum13633bb2007-04-13 18:42:35 +0000620 @property
621 def name(self):
622 return self._name
623
Georg Brandlf91197c2008-04-09 07:33:01 +0000624 # XXX(gb): _FileIO already has a mode property
Guido van Rossum13633bb2007-04-13 18:42:35 +0000625 @property
626 def mode(self):
627 return self._mode
628
Guido van Rossuma9e20242007-03-08 00:43:48 +0000629
Guido van Rossumcce92b22007-04-10 14:41:39 +0000630class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000631
632 """Base class for buffered IO objects.
633
634 The main difference with RawIOBase is that the read() method
635 supports omitting the size argument, and does not have a default
636 implementation that defers to readinto().
637
638 In addition, read(), readinto() and write() may raise
639 BlockingIOError if the underlying raw stream is in non-blocking
640 mode and not ready; unlike their raw counterparts, they will never
641 return None.
642
643 A typical implementation should not inherit from a RawIOBase
644 implementation, but wrap one.
645 """
646
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000647 def read(self, n: int = None) -> bytes:
648 """read(n: int = None) -> bytes. Read and return up to n bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000649
Guido van Rossum024da5c2007-05-17 23:59:11 +0000650 If the argument is omitted, None, or negative, reads and
651 returns all data until EOF.
Guido van Rossum141f7672007-04-10 00:22:16 +0000652
653 If the argument is positive, and the underlying raw stream is
654 not 'interactive', multiple raw reads may be issued to satisfy
655 the byte count (unless EOF is reached first). But for
656 interactive raw streams (XXX and for pipes?), at most one raw
657 read will be issued, and a short result does not imply that
658 EOF is imminent.
659
660 Returns an empty bytes array on EOF.
661
662 Raises BlockingIOError if the underlying raw stream has no
663 data at the moment.
664 """
665 self._unsupported("read")
666
Benjamin Petersonca2b0152008-04-07 22:27:34 +0000667 def readinto(self, b: bytearray) -> int:
668 """readinto(b: bytearray) -> int. Read up to len(b) bytes into b.
Guido van Rossum141f7672007-04-10 00:22:16 +0000669
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000670 Like read(), this may issue multiple reads to the underlying raw
671 stream, unless the latter is 'interactive'.
Guido van Rossum141f7672007-04-10 00:22:16 +0000672
673 Returns the number of bytes read (0 for EOF).
674
675 Raises BlockingIOError if the underlying raw stream has no
676 data at the moment.
677 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000678 # XXX This ought to work with anything that supports the buffer API
Guido van Rossum87429772007-04-10 21:06:59 +0000679 data = self.read(len(b))
680 n = len(data)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000681 try:
682 b[:n] = data
683 except TypeError as err:
684 import array
685 if not isinstance(b, array.array):
686 raise err
687 b[:n] = array.array('b', data)
Guido van Rossum87429772007-04-10 21:06:59 +0000688 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000689
690 def write(self, b: bytes) -> int:
691 """write(b: bytes) -> int. Write the given buffer to the IO stream.
692
693 Returns the number of bytes written, which is never less than
694 len(b).
695
696 Raises BlockingIOError if the buffer is full and the
697 underlying raw stream cannot accept more data at the moment.
698 """
699 self._unsupported("write")
700
701
702class _BufferedIOMixin(BufferedIOBase):
703
704 """A mixin implementation of BufferedIOBase with an underlying raw stream.
705
706 This passes most requests on to the underlying raw stream. It
707 does *not* provide implementations of read(), readinto() or
708 write().
709 """
710
711 def __init__(self, raw):
712 self.raw = raw
713
714 ### Positioning ###
715
716 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000717 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000718
719 def tell(self):
720 return self.raw.tell()
721
722 def truncate(self, pos=None):
Guido van Rossum79b79ee2007-10-25 23:21:03 +0000723 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
724 # and a flush may be necessary to synch both views of the current
725 # file state.
726 self.flush()
Guido van Rossum57233cb2007-10-26 17:19:33 +0000727
728 if pos is None:
729 pos = self.tell()
730 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000731
732 ### Flush and close ###
733
734 def flush(self):
735 self.raw.flush()
736
737 def close(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000738 if not self.closed:
Guido van Rossum33e7a8e2007-07-22 20:38:07 +0000739 try:
740 self.flush()
741 except IOError:
742 pass # If flush() fails, just give up
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000743 self.raw.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000744
745 ### Inquiries ###
746
747 def seekable(self):
748 return self.raw.seekable()
749
750 def readable(self):
751 return self.raw.readable()
752
753 def writable(self):
754 return self.raw.writable()
755
756 @property
757 def closed(self):
758 return self.raw.closed
759
760 ### Lower-level APIs ###
761
762 def fileno(self):
763 return self.raw.fileno()
764
765 def isatty(self):
766 return self.raw.isatty()
767
768
Guido van Rossum024da5c2007-05-17 23:59:11 +0000769class BytesIO(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000770
Guido van Rossum024da5c2007-05-17 23:59:11 +0000771 """Buffered I/O implementation using an in-memory bytes buffer."""
Guido van Rossum28524c72007-02-27 05:47:44 +0000772
Guido van Rossum024da5c2007-05-17 23:59:11 +0000773 def __init__(self, initial_bytes=None):
Guido van Rossum254348e2007-11-21 19:29:53 +0000774 buf = bytearray()
Guido van Rossum024da5c2007-05-17 23:59:11 +0000775 if initial_bytes is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000776 buf += initial_bytes
777 self._buffer = buf
Guido van Rossum28524c72007-02-27 05:47:44 +0000778 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000779
780 def getvalue(self):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000781 """getvalue() -> bytes Return the bytes value (contents) of the buffer
782 """
Guido van Rossum98297ee2007-11-06 21:34:58 +0000783 return bytes(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000784
Guido van Rossum024da5c2007-05-17 23:59:11 +0000785 def read(self, n=None):
786 if n is None:
787 n = -1
Guido van Rossum141f7672007-04-10 00:22:16 +0000788 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000789 n = len(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000790 newpos = min(len(self._buffer), self._pos + n)
791 b = self._buffer[self._pos : newpos]
792 self._pos = newpos
Guido van Rossum98297ee2007-11-06 21:34:58 +0000793 return bytes(b)
Guido van Rossum28524c72007-02-27 05:47:44 +0000794
Guido van Rossum024da5c2007-05-17 23:59:11 +0000795 def read1(self, n):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000796 """In BytesIO, this is the same as read.
797 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000798 return self.read(n)
799
Guido van Rossum28524c72007-02-27 05:47:44 +0000800 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000801 if self.closed:
802 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +0000803 if isinstance(b, str):
804 raise TypeError("can't write str to binary stream")
Guido van Rossum28524c72007-02-27 05:47:44 +0000805 n = len(b)
806 newpos = self._pos + n
Guido van Rossumb972a782007-07-21 00:25:15 +0000807 if newpos > len(self._buffer):
808 # Inserts null bytes between the current end of the file
809 # and the new write position.
Guido van Rossuma74184e2007-08-29 04:05:57 +0000810 padding = b'\x00' * (newpos - len(self._buffer) - n)
Guido van Rossumb972a782007-07-21 00:25:15 +0000811 self._buffer[self._pos:newpos - n] = padding
Guido van Rossum28524c72007-02-27 05:47:44 +0000812 self._buffer[self._pos:newpos] = b
813 self._pos = newpos
814 return n
815
816 def seek(self, pos, whence=0):
Christian Heimes3ab4f652007-11-09 01:27:29 +0000817 try:
818 pos = pos.__index__()
819 except AttributeError as err:
820 raise TypeError("an integer is required") from err
Guido van Rossum28524c72007-02-27 05:47:44 +0000821 if whence == 0:
822 self._pos = max(0, pos)
823 elif whence == 1:
824 self._pos = max(0, self._pos + pos)
825 elif whence == 2:
826 self._pos = max(0, len(self._buffer) + pos)
827 else:
828 raise IOError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000829 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000830
831 def tell(self):
832 return self._pos
833
834 def truncate(self, pos=None):
835 if pos is None:
836 pos = self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000837 del self._buffer[pos:]
Guido van Rossum87429772007-04-10 21:06:59 +0000838 return pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000839
840 def readable(self):
841 return True
842
843 def writable(self):
844 return True
845
846 def seekable(self):
847 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000848
849
Guido van Rossum141f7672007-04-10 00:22:16 +0000850class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000851
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000852 """BufferedReader(raw[, buffer_size])
853
854 A buffer for a readable, sequential BaseRawIO object.
855
856 The constructor creates a BufferedReader for the given readable raw
857 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
858 is used.
859 """
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000860
Guido van Rossum78892e42007-04-06 17:31:18 +0000861 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000862 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000863 """
Guido van Rossum5abbf752007-08-27 17:39:33 +0000864 raw._checkReadable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000865 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum01a27522007-03-07 01:00:12 +0000866 self._read_buf = b""
Guido van Rossum78892e42007-04-06 17:31:18 +0000867 self.buffer_size = buffer_size
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000868
Guido van Rossum024da5c2007-05-17 23:59:11 +0000869 def read(self, n=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000870 """Read n bytes.
871
872 Returns exactly n bytes of data unless the underlying raw IO
Walter Dörwalda3270002007-05-29 19:13:29 +0000873 stream reaches EOF or if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000874 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000875 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000876 """
Guido van Rossum024da5c2007-05-17 23:59:11 +0000877 if n is None:
878 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +0000879 nodata_val = b""
Guido van Rossum141f7672007-04-10 00:22:16 +0000880 while n < 0 or len(self._read_buf) < n:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000881 to_read = max(self.buffer_size,
882 n if n is not None else 2*len(self._read_buf))
Guido van Rossum78892e42007-04-06 17:31:18 +0000883 current = self.raw.read(to_read)
Guido van Rossum78892e42007-04-06 17:31:18 +0000884 if current in (b"", None):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000885 nodata_val = current
886 break
Guido van Rossum01a27522007-03-07 01:00:12 +0000887 self._read_buf += current
888 if self._read_buf:
Guido van Rossum141f7672007-04-10 00:22:16 +0000889 if n < 0:
Guido van Rossum01a27522007-03-07 01:00:12 +0000890 n = len(self._read_buf)
891 out = self._read_buf[:n]
892 self._read_buf = self._read_buf[n:]
893 else:
894 out = nodata_val
895 return out
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000896
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000897 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +0000898 """Returns buffered bytes without advancing the position.
899
900 The argument indicates a desired minimal number of bytes; we
901 do at most one raw read to satisfy it. We never return more
902 than self.buffer_size.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000903 """
904 want = min(n, self.buffer_size)
905 have = len(self._read_buf)
906 if have < want:
907 to_read = self.buffer_size - have
908 current = self.raw.read(to_read)
909 if current:
910 self._read_buf += current
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000911 return self._read_buf
Guido van Rossum13633bb2007-04-13 18:42:35 +0000912
913 def read1(self, n):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000914 """Reads up to n bytes, with at most one read() system call."""
915 # Returns up to n bytes. If at least one byte is buffered, we
916 # only return buffered bytes. Otherwise, we do one raw read.
Guido van Rossum13633bb2007-04-13 18:42:35 +0000917 if n <= 0:
918 return b""
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +0000919 self.peek(1)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000920 return self.read(min(n, len(self._read_buf)))
921
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000922 def tell(self):
923 return self.raw.tell() - len(self._read_buf)
924
925 def seek(self, pos, whence=0):
926 if whence == 1:
927 pos -= len(self._read_buf)
Guido van Rossum53807da2007-04-10 19:01:47 +0000928 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000929 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +0000930 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000931
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000932
Guido van Rossum141f7672007-04-10 00:22:16 +0000933class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000934
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000935 """BufferedWriter(raw[, buffer_size[, max_buffer_size]])
936
937 A buffer for a writeable sequential RawIO object.
938
939 The constructor creates a BufferedWriter for the given writeable raw
940 stream. If the buffer_size is not given, it defaults to
941 DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
942 twice the buffer size.
943 """
Guido van Rossum78892e42007-04-06 17:31:18 +0000944
Guido van Rossum141f7672007-04-10 00:22:16 +0000945 def __init__(self, raw,
946 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000947 raw._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000948 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000949 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +0000950 self.max_buffer_size = (2*buffer_size
951 if max_buffer_size is None
952 else max_buffer_size)
Guido van Rossum254348e2007-11-21 19:29:53 +0000953 self._write_buf = bytearray()
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000954
955 def write(self, b):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000956 if self.closed:
957 raise ValueError("write to closed file")
Guido van Rossuma74184e2007-08-29 04:05:57 +0000958 if isinstance(b, str):
959 raise TypeError("can't write str to binary stream")
Guido van Rossum01a27522007-03-07 01:00:12 +0000960 # XXX we can implement some more tricks to try and avoid partial writes
Guido van Rossum01a27522007-03-07 01:00:12 +0000961 if len(self._write_buf) > self.buffer_size:
962 # We're full, so let's pre-flush the buffer
963 try:
964 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000965 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000966 # We can't accept anything else.
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000967 # XXX Why not just let the exception pass through?
Guido van Rossum141f7672007-04-10 00:22:16 +0000968 raise BlockingIOError(e.errno, e.strerror, 0)
Guido van Rossumd4103952007-04-12 05:44:49 +0000969 before = len(self._write_buf)
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000970 self._write_buf.extend(b)
Guido van Rossumd4103952007-04-12 05:44:49 +0000971 written = len(self._write_buf) - before
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000972 if len(self._write_buf) > self.buffer_size:
Guido van Rossum01a27522007-03-07 01:00:12 +0000973 try:
974 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000975 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000976 if (len(self._write_buf) > self.max_buffer_size):
977 # We've hit max_buffer_size. We have to accept a partial
978 # write and cut back our buffer.
979 overage = len(self._write_buf) - self.max_buffer_size
980 self._write_buf = self._write_buf[:self.max_buffer_size]
Guido van Rossum141f7672007-04-10 00:22:16 +0000981 raise BlockingIOError(e.errno, e.strerror, overage)
Guido van Rossumd4103952007-04-12 05:44:49 +0000982 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000983
984 def flush(self):
Guido van Rossum4b5386f2007-07-10 09:12:49 +0000985 if self.closed:
986 raise ValueError("flush of closed file")
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000987 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +0000988 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000989 while self._write_buf:
990 n = self.raw.write(self._write_buf)
991 del self._write_buf[:n]
992 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000993 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000994 n = e.characters_written
995 del self._write_buf[:n]
996 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000997 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000998
999 def tell(self):
1000 return self.raw.tell() + len(self._write_buf)
1001
1002 def seek(self, pos, whence=0):
1003 self.flush()
Guido van Rossum53807da2007-04-10 19:01:47 +00001004 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001005
Guido van Rossum01a27522007-03-07 01:00:12 +00001006
Guido van Rossum141f7672007-04-10 00:22:16 +00001007class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001008
Guido van Rossum01a27522007-03-07 01:00:12 +00001009 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001010
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001011 A buffered reader object and buffered writer object put together to
1012 form a sequential IO object that can read and write. This is typically
1013 used with a socket or two-way pipe.
Guido van Rossum78892e42007-04-06 17:31:18 +00001014
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001015 reader and writer are RawIOBase objects that are readable and
1016 writeable respectively. If the buffer_size is omitted it defaults to
1017 DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
1018 defaults to twice the buffer size.
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001019 """
1020
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001021 # XXX The usefulness of this (compared to having two separate IO
1022 # objects) is questionable.
1023
Guido van Rossum141f7672007-04-10 00:22:16 +00001024 def __init__(self, reader, writer,
1025 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1026 """Constructor.
1027
1028 The arguments are two RawIO instances.
1029 """
Guido van Rossum5abbf752007-08-27 17:39:33 +00001030 reader._checkReadable()
1031 writer._checkWritable()
Guido van Rossum141f7672007-04-10 00:22:16 +00001032 self.reader = BufferedReader(reader, buffer_size)
1033 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001034
Guido van Rossum024da5c2007-05-17 23:59:11 +00001035 def read(self, n=None):
1036 if n is None:
1037 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001038 return self.reader.read(n)
1039
Guido van Rossum141f7672007-04-10 00:22:16 +00001040 def readinto(self, b):
1041 return self.reader.readinto(b)
1042
Guido van Rossum01a27522007-03-07 01:00:12 +00001043 def write(self, b):
1044 return self.writer.write(b)
1045
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001046 def peek(self, n=0):
1047 return self.reader.peek(n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001048
1049 def read1(self, n):
1050 return self.reader.read1(n)
1051
Guido van Rossum01a27522007-03-07 01:00:12 +00001052 def readable(self):
1053 return self.reader.readable()
1054
1055 def writable(self):
1056 return self.writer.writable()
1057
1058 def flush(self):
1059 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +00001060
Guido van Rossum01a27522007-03-07 01:00:12 +00001061 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +00001062 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +00001063 self.reader.close()
1064
1065 def isatty(self):
1066 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +00001067
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001068 @property
1069 def closed(self):
Guido van Rossum141f7672007-04-10 00:22:16 +00001070 return self.writer.closed()
Guido van Rossum01a27522007-03-07 01:00:12 +00001071
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001072
Guido van Rossum141f7672007-04-10 00:22:16 +00001073class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +00001074
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001075 """BufferedRandom(raw[, buffer_size[, max_buffer_size]])
1076
1077 A buffered interface to random access streams.
1078
1079 The constructor creates a reader and writer for a seekable stream,
1080 raw, given in the first argument. If the buffer_size is omitted it
1081 defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
1082 writer) defaults to twice the buffer size.
1083 """
Guido van Rossum78892e42007-04-06 17:31:18 +00001084
Guido van Rossum141f7672007-04-10 00:22:16 +00001085 def __init__(self, raw,
1086 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum5abbf752007-08-27 17:39:33 +00001087 raw._checkSeekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001088 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +00001089 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1090
Guido van Rossum01a27522007-03-07 01:00:12 +00001091 def seek(self, pos, whence=0):
1092 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001093 # First do the raw seek, then empty the read buffer, so that
1094 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +00001095 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +00001096 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +00001097 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +00001098
1099 def tell(self):
1100 if (self._write_buf):
1101 return self.raw.tell() + len(self._write_buf)
1102 else:
1103 return self.raw.tell() - len(self._read_buf)
1104
Guido van Rossum024da5c2007-05-17 23:59:11 +00001105 def read(self, n=None):
1106 if n is None:
1107 n = -1
Guido van Rossum01a27522007-03-07 01:00:12 +00001108 self.flush()
1109 return BufferedReader.read(self, n)
1110
Guido van Rossum141f7672007-04-10 00:22:16 +00001111 def readinto(self, b):
1112 self.flush()
1113 return BufferedReader.readinto(self, b)
1114
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001115 def peek(self, n=0):
Guido van Rossum13633bb2007-04-13 18:42:35 +00001116 self.flush()
Ka-Ping Yee7a0d3982008-03-17 17:34:48 +00001117 return BufferedReader.peek(self, n)
Guido van Rossum13633bb2007-04-13 18:42:35 +00001118
1119 def read1(self, n):
1120 self.flush()
1121 return BufferedReader.read1(self, n)
1122
Guido van Rossum01a27522007-03-07 01:00:12 +00001123 def write(self, b):
Guido van Rossum78892e42007-04-06 17:31:18 +00001124 if self._read_buf:
1125 self.raw.seek(-len(self._read_buf), 1) # Undo readahead
1126 self._read_buf = b""
Guido van Rossum01a27522007-03-07 01:00:12 +00001127 return BufferedWriter.write(self, b)
1128
Guido van Rossum78892e42007-04-06 17:31:18 +00001129
Guido van Rossumcce92b22007-04-10 14:41:39 +00001130class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +00001131
1132 """Base class for text I/O.
1133
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001134 This class provides a character and line based interface to stream
1135 I/O. There is no readinto method because Python's character strings
1136 are immutable. There is no public constructor.
Guido van Rossum78892e42007-04-06 17:31:18 +00001137 """
1138
1139 def read(self, n: int = -1) -> str:
1140 """read(n: int = -1) -> str. Read at most n characters from stream.
1141
1142 Read from underlying buffer until we have n characters or we hit EOF.
1143 If n is negative or omitted, read until EOF.
1144 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001145 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +00001146
Guido van Rossum9b76da62007-04-11 01:09:03 +00001147 def write(self, s: str) -> int:
1148 """write(s: str) -> int. Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001149 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +00001150
Guido van Rossum9b76da62007-04-11 01:09:03 +00001151 def truncate(self, pos: int = None) -> int:
1152 """truncate(pos: int = None) -> int. Truncate size to pos."""
1153 self.flush()
1154 if pos is None:
1155 pos = self.tell()
1156 self.seek(pos)
1157 return self.buffer.truncate()
1158
Guido van Rossum78892e42007-04-06 17:31:18 +00001159 def readline(self) -> str:
1160 """readline() -> str. Read until newline or EOF.
1161
1162 Returns an empty string if EOF is hit immediately.
1163 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001164 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +00001165
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001166 @property
1167 def encoding(self):
1168 """Subclasses should override."""
1169 return None
1170
Guido van Rossum8358db22007-08-18 21:39:55 +00001171 @property
1172 def newlines(self):
1173 """newlines -> None | str | tuple of str. Line endings translated
1174 so far.
1175
1176 Only line endings translated during reading are considered.
1177
1178 Subclasses should override.
1179 """
1180 return None
1181
Guido van Rossum78892e42007-04-06 17:31:18 +00001182
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001183class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001184 r"""Codec used when reading a file in universal newlines mode. It wraps
1185 another incremental decoder, translating \r\n and \r into \n. It also
1186 records the types of newlines encountered. When used with
1187 translate=False, it ensures that the newline sequence is returned in
1188 one piece.
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001189 """
1190 def __init__(self, decoder, translate, errors='strict'):
1191 codecs.IncrementalDecoder.__init__(self, errors=errors)
1192 self.buffer = b''
1193 self.translate = translate
1194 self.decoder = decoder
1195 self.seennl = 0
1196
1197 def decode(self, input, final=False):
1198 # decode input (with the eventual \r from a previous pass)
1199 if self.buffer:
1200 input = self.buffer + input
1201
1202 output = self.decoder.decode(input, final=final)
1203
1204 # retain last \r even when not translating data:
1205 # then readline() is sure to get \r\n in one pass
1206 if output.endswith("\r") and not final:
1207 output = output[:-1]
1208 self.buffer = b'\r'
1209 else:
1210 self.buffer = b''
1211
1212 # Record which newlines are read
1213 crlf = output.count('\r\n')
1214 cr = output.count('\r') - crlf
1215 lf = output.count('\n') - crlf
1216 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1217 | (crlf and self._CRLF)
1218
1219 if self.translate:
1220 if crlf:
1221 output = output.replace("\r\n", "\n")
1222 if cr:
1223 output = output.replace("\r", "\n")
1224
1225 return output
1226
1227 def getstate(self):
1228 buf, flag = self.decoder.getstate()
1229 return buf + self.buffer, flag
1230
1231 def setstate(self, state):
1232 buf, flag = state
1233 if buf.endswith(b'\r'):
1234 self.buffer = b'\r'
1235 buf = buf[:-1]
1236 else:
1237 self.buffer = b''
1238 self.decoder.setstate((buf, flag))
1239
1240 def reset(self):
Alexandre Vassalottic3d7fe02007-12-28 01:24:22 +00001241 self.seennl = 0
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001242 self.buffer = b''
1243 self.decoder.reset()
1244
1245 _LF = 1
1246 _CR = 2
1247 _CRLF = 4
1248
1249 @property
1250 def newlines(self):
1251 return (None,
1252 "\n",
1253 "\r",
1254 ("\r", "\n"),
1255 "\r\n",
1256 ("\n", "\r\n"),
1257 ("\r", "\r\n"),
1258 ("\r", "\n", "\r\n")
1259 )[self.seennl]
1260
1261
Guido van Rossum78892e42007-04-06 17:31:18 +00001262class TextIOWrapper(TextIOBase):
1263
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001264 r"""TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
Guido van Rossum78892e42007-04-06 17:31:18 +00001265
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001266 Character and line based layer over a BufferedIOBase object, buffer.
1267
1268 encoding gives the name of the encoding that the stream will be
1269 decoded or encoded with. It defaults to locale.getpreferredencoding.
1270
1271 errors determines the strictness of encoding and decoding (see the
1272 codecs.register) and defaults to "strict".
1273
1274 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1275 handling of line endings. If it is None, universal newlines is
1276 enabled. With this enabled, on input, the lines endings '\n', '\r',
1277 or '\r\n' are translated to '\n' before being returned to the
1278 caller. Conversely, on output, '\n' is translated to the system
1279 default line seperator, os.linesep. If newline is any other of its
1280 legal values, that newline becomes the newline when the file is read
1281 and it is returned untranslated. On output, '\n' is converted to the
1282 newline.
1283
1284 If line_buffering is True, a call to flush is implied when a call to
1285 write contains a newline character.
Guido van Rossum78892e42007-04-06 17:31:18 +00001286 """
1287
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001288 _CHUNK_SIZE = 128
Guido van Rossum78892e42007-04-06 17:31:18 +00001289
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001290 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1291 line_buffering=False):
Guido van Rossum8358db22007-08-18 21:39:55 +00001292 if newline not in (None, "", "\n", "\r", "\r\n"):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001293 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +00001294 if encoding is None:
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001295 try:
1296 encoding = os.device_encoding(buffer.fileno())
Brett Cannon041683d2007-10-11 23:08:53 +00001297 except (AttributeError, UnsupportedOperation):
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +00001298 pass
1299 if encoding is None:
Martin v. Löwisd78d3b42007-08-11 15:36:45 +00001300 try:
1301 import locale
1302 except ImportError:
1303 # Importing locale may fail if Python is being built
1304 encoding = "ascii"
1305 else:
1306 encoding = locale.getpreferredencoding()
Guido van Rossum78892e42007-04-06 17:31:18 +00001307
Christian Heimes8bd14fb2007-11-08 16:34:32 +00001308 if not isinstance(encoding, str):
1309 raise ValueError("invalid encoding: %r" % encoding)
1310
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001311 if errors is None:
1312 errors = "strict"
1313 else:
1314 if not isinstance(errors, str):
1315 raise ValueError("invalid errors: %r" % errors)
1316
Guido van Rossum78892e42007-04-06 17:31:18 +00001317 self.buffer = buffer
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001318 self._line_buffering = line_buffering
Guido van Rossum78892e42007-04-06 17:31:18 +00001319 self._encoding = encoding
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001320 self._errors = errors
Guido van Rossum8358db22007-08-18 21:39:55 +00001321 self._readuniversal = not newline
1322 self._readtranslate = newline is None
1323 self._readnl = newline
1324 self._writetranslate = newline != ''
1325 self._writenl = newline or os.linesep
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001326 self._encoder = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001327 self._decoder = None
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001328 self._decoded_chars = '' # buffer for text returned from decoder
1329 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001330 self._snapshot = None # info for reconstructing decoder state
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001331 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001332
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001333 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1334 # where dec_flags is the second (integer) item of the decoder state
1335 # and next_input is the chunk of input bytes that comes next after the
1336 # snapshot point. We use this to reconstruct decoder states in tell().
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001337
1338 # Naming convention:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001339 # - "bytes_..." for integer variables that count input bytes
1340 # - "chars_..." for integer variables that count decoded characters
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001341
Guido van Rossumfc3436b2007-05-24 17:58:06 +00001342 @property
1343 def encoding(self):
1344 return self._encoding
1345
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001346 @property
1347 def errors(self):
1348 return self._errors
1349
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001350 @property
1351 def line_buffering(self):
1352 return self._line_buffering
1353
Ka-Ping Yeeddaa7062008-03-17 20:35:15 +00001354 def seekable(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001355 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +00001356
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001357 def flush(self):
1358 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001359 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001360
1361 def close(self):
Guido van Rossum33e7a8e2007-07-22 20:38:07 +00001362 try:
1363 self.flush()
1364 except:
1365 pass # If flush() fails, just give up
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001366 self.buffer.close()
1367
1368 @property
1369 def closed(self):
1370 return self.buffer.closed
1371
Guido van Rossum9be55972007-04-07 02:59:27 +00001372 def fileno(self):
1373 return self.buffer.fileno()
1374
Guido van Rossum859b5ec2007-05-27 09:14:51 +00001375 def isatty(self):
1376 return self.buffer.isatty()
1377
Guido van Rossum78892e42007-04-06 17:31:18 +00001378 def write(self, s: str):
Guido van Rossum4b5386f2007-07-10 09:12:49 +00001379 if self.closed:
1380 raise ValueError("write to closed file")
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001381 if not isinstance(s, str):
Guido van Rossumdcce8392007-08-29 18:10:08 +00001382 raise TypeError("can't write %s to text stream" %
1383 s.__class__.__name__)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001384 length = len(s)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001385 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
Guido van Rossum8358db22007-08-18 21:39:55 +00001386 if haslf and self._writetranslate and self._writenl != "\n":
1387 s = s.replace("\n", self._writenl)
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001388 encoder = self._encoder or self._get_encoder()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001389 # XXX What if we were just reading?
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001390 b = encoder.encode(s)
Guido van Rossum8358db22007-08-18 21:39:55 +00001391 self.buffer.write(b)
Guido van Rossumf64db9f2007-12-06 01:04:26 +00001392 if self._line_buffering and (haslf or "\r" in s):
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001393 self.flush()
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001394 self._snapshot = None
1395 if self._decoder:
1396 self._decoder.reset()
1397 return length
Guido van Rossum78892e42007-04-06 17:31:18 +00001398
Alexandre Vassalottia38f73b2008-01-07 18:30:48 +00001399 def _get_encoder(self):
1400 make_encoder = codecs.getincrementalencoder(self._encoding)
1401 self._encoder = make_encoder(self._errors)
1402 return self._encoder
1403
Guido van Rossum78892e42007-04-06 17:31:18 +00001404 def _get_decoder(self):
1405 make_decoder = codecs.getincrementaldecoder(self._encoding)
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001406 decoder = make_decoder(self._errors)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001407 if self._readuniversal:
1408 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1409 self._decoder = decoder
Guido van Rossum78892e42007-04-06 17:31:18 +00001410 return decoder
1411
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001412 # The following three methods implement an ADT for _decoded_chars.
1413 # Text returned from the decoder is buffered here until the client
1414 # requests it by calling our read() or readline() method.
1415 def _set_decoded_chars(self, chars):
1416 """Set the _decoded_chars buffer."""
1417 self._decoded_chars = chars
1418 self._decoded_chars_used = 0
1419
1420 def _get_decoded_chars(self, n=None):
1421 """Advance into the _decoded_chars buffer."""
1422 offset = self._decoded_chars_used
1423 if n is None:
1424 chars = self._decoded_chars[offset:]
1425 else:
1426 chars = self._decoded_chars[offset:offset + n]
1427 self._decoded_chars_used += len(chars)
1428 return chars
1429
1430 def _rewind_decoded_chars(self, n):
1431 """Rewind the _decoded_chars buffer."""
1432 if self._decoded_chars_used < n:
1433 raise AssertionError("rewind decoded_chars out of bounds")
1434 self._decoded_chars_used -= n
1435
Guido van Rossum9b76da62007-04-11 01:09:03 +00001436 def _read_chunk(self):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001437 """
1438 Read and decode the next chunk of data from the BufferedReader.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001439 """
1440
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001441 # The return value is True unless EOF was reached. The decoded
1442 # string is placed in self._decoded_chars (replacing its previous
1443 # value). The entire input chunk is sent to the decoder, though
1444 # some of it may remain buffered in the decoder, yet to be
1445 # converted.
1446
Guido van Rossum5abbf752007-08-27 17:39:33 +00001447 if self._decoder is None:
1448 raise ValueError("no decoder")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001449
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001450 if self._telling:
1451 # To prepare for tell(), we need to snapshot a point in the
1452 # file where the decoder's input buffer is empty.
Guido van Rossum9b76da62007-04-11 01:09:03 +00001453
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001454 dec_buffer, dec_flags = self._decoder.getstate()
1455 # Given this, we know there was a valid snapshot point
1456 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001457
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001458 # Read a chunk, decode it, and put the result in self._decoded_chars.
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001459 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1460 eof = not input_chunk
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001461 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001462
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001463 if self._telling:
1464 # At the snapshot point, len(dec_buffer) bytes before the read,
1465 # the next input to be decoded is dec_buffer + input_chunk.
1466 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1467
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001468 return not eof
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001469
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001470 def _pack_cookie(self, position, dec_flags=0,
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001471 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001472 # The meaning of a tell() cookie is: seek to position, set the
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001473 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001474 # into the decoder with need_eof as the EOF flag, then skip
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001475 # chars_to_skip characters of the decoded result. For most simple
1476 # decoders, tell() will often just give a byte offset in the file.
1477 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1478 (chars_to_skip<<192) | bool(need_eof)<<256)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001479
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001480 def _unpack_cookie(self, bigint):
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001481 rest, position = divmod(bigint, 1<<64)
1482 rest, dec_flags = divmod(rest, 1<<64)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001483 rest, bytes_to_feed = divmod(rest, 1<<64)
1484 need_eof, chars_to_skip = divmod(rest, 1<<64)
1485 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
Guido van Rossum9b76da62007-04-11 01:09:03 +00001486
1487 def tell(self):
1488 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001489 raise IOError("underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001490 if not self._telling:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001491 raise IOError("telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001492 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001493 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001494 decoder = self._decoder
1495 if decoder is None or self._snapshot is None:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001496 if self._decoded_chars:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001497 # This should never happen.
1498 raise AssertionError("pending decoded text")
Guido van Rossumcba608c2007-04-11 14:19:59 +00001499 return position
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001500
1501 # Skip backward to the snapshot point (see _read_chunk).
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001502 dec_flags, next_input = self._snapshot
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001503 position -= len(next_input)
1504
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001505 # How many decoded characters have been used up since the snapshot?
1506 chars_to_skip = self._decoded_chars_used
1507 if chars_to_skip == 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001508 # We haven't moved from the snapshot point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001509 return self._pack_cookie(position, dec_flags)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001510
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001511 # Starting from the snapshot position, we will walk the decoder
1512 # forward until it gives us enough decoded characters.
Guido van Rossumd76e7792007-04-17 02:38:04 +00001513 saved_state = decoder.getstate()
1514 try:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001515 # Note our initial start point.
1516 decoder.setstate((b'', dec_flags))
1517 start_pos = position
1518 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001519 need_eof = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001520
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001521 # Feed the decoder one byte at a time. As we go, note the
1522 # nearest "safe start point" before the current location
1523 # (a point where the decoder has nothing buffered, so seek()
1524 # can safely start from there and advance to this location).
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001525 next_byte = bytearray(1)
1526 for next_byte[0] in next_input:
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001527 bytes_fed += 1
1528 chars_decoded += len(decoder.decode(next_byte))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001529 dec_buffer, dec_flags = decoder.getstate()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001530 if not dec_buffer and chars_decoded <= chars_to_skip:
1531 # Decoder buffer is empty, so this is a safe start point.
1532 start_pos += bytes_fed
1533 chars_to_skip -= chars_decoded
1534 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1535 if chars_decoded >= chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001536 break
1537 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001538 # We didn't get enough decoded data; signal EOF to get more.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001539 chars_decoded += len(decoder.decode(b'', final=True))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001540 need_eof = 1
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001541 if chars_decoded < chars_to_skip:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001542 raise IOError("can't reconstruct logical file position")
1543
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001544 # The returned cookie corresponds to the last safe start point.
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001545 return self._pack_cookie(
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001546 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001547 finally:
1548 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001549
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001550 def seek(self, cookie, whence=0):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001551 if not self._seekable:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001552 raise IOError("underlying stream is not seekable")
1553 if whence == 1: # seek relative to current position
1554 if cookie != 0:
1555 raise IOError("can't do nonzero cur-relative seeks")
1556 # Seeking to the current position should attempt to
1557 # sync the underlying buffer with the current position.
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001558 whence = 0
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001559 cookie = self.tell()
1560 if whence == 2: # seek relative to end of file
1561 if cookie != 0:
1562 raise IOError("can't do nonzero end-relative seeks")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001563 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001564 position = self.buffer.seek(0, 2)
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001565 self._set_decoded_chars('')
1566 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001567 if self._decoder:
1568 self._decoder.reset()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001569 return position
Guido van Rossum9b76da62007-04-11 01:09:03 +00001570 if whence != 0:
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001571 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
Guido van Rossum9b76da62007-04-11 01:09:03 +00001572 (whence,))
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001573 if cookie < 0:
1574 raise ValueError("negative seek position %r" % (cookie,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001575 self.flush()
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001576
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001577 # The strategy of seek() is to go back to the safe start point
1578 # and replay the effect of read(chars_to_skip) from there.
1579 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001580 self._unpack_cookie(cookie)
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001581
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001582 # Seek back to the safe start point.
1583 self.buffer.seek(start_pos)
1584 self._set_decoded_chars('')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001585 self._snapshot = None
1586
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001587 # Restore the decoder to its state from the safe start point.
1588 if self._decoder or dec_flags or chars_to_skip:
1589 self._decoder = self._decoder or self._get_decoder()
1590 self._decoder.setstate((b'', dec_flags))
1591 self._snapshot = (dec_flags, b'')
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001592
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001593 if chars_to_skip:
1594 # Just like _read_chunk, feed the decoder and save a snapshot.
1595 input_chunk = self.buffer.read(bytes_to_feed)
1596 self._set_decoded_chars(
1597 self._decoder.decode(input_chunk, need_eof))
1598 self._snapshot = (dec_flags, input_chunk)
1599
1600 # Skip chars_to_skip of the decoded characters.
1601 if len(self._decoded_chars) < chars_to_skip:
1602 raise IOError("can't restore logical file position")
1603 self._decoded_chars_used = chars_to_skip
1604
1605 return cookie
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001606
Guido van Rossum024da5c2007-05-17 23:59:11 +00001607 def read(self, n=None):
1608 if n is None:
1609 n = -1
Guido van Rossum78892e42007-04-06 17:31:18 +00001610 decoder = self._decoder or self._get_decoder()
Guido van Rossum78892e42007-04-06 17:31:18 +00001611 if n < 0:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001612 # Read everything.
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001613 result = (self._get_decoded_chars() +
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001614 decoder.decode(self.buffer.read(), final=True))
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001615 self._set_decoded_chars('')
1616 self._snapshot = None
Ka-Ping Yeef44c7e82008-03-18 04:51:32 +00001617 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001618 else:
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001619 # Keep reading chunks until we have n characters to return.
1620 eof = False
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001621 result = self._get_decoded_chars(n)
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001622 while len(result) < n and not eof:
1623 eof = not self._read_chunk()
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001624 result += self._get_decoded_chars(n - len(result))
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001625 return result
Guido van Rossum78892e42007-04-06 17:31:18 +00001626
Guido van Rossum024da5c2007-05-17 23:59:11 +00001627 def __next__(self):
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001628 self._telling = False
1629 line = self.readline()
1630 if not line:
1631 self._snapshot = None
1632 self._telling = self._seekable
1633 raise StopIteration
1634 return line
1635
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001636 def readline(self, limit=None):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001637 if limit is None:
1638 limit = -1
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001639
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001640 # Grab all the decoded text (we will rewind any extra bits later).
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001641 line = self._get_decoded_chars()
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001642
Guido van Rossum78892e42007-04-06 17:31:18 +00001643 start = 0
1644 decoder = self._decoder or self._get_decoder()
1645
Guido van Rossum8358db22007-08-18 21:39:55 +00001646 pos = endpos = None
Guido van Rossum78892e42007-04-06 17:31:18 +00001647 while True:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001648 if self._readtranslate:
1649 # Newlines are already translated, only search for \n
1650 pos = line.find('\n', start)
1651 if pos >= 0:
1652 endpos = pos + 1
1653 break
1654 else:
1655 start = len(line)
1656
1657 elif self._readuniversal:
Guido van Rossum8358db22007-08-18 21:39:55 +00001658 # Universal newline search. Find any of \r, \r\n, \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001659 # The decoder ensures that \r\n are not split in two pieces
Guido van Rossum78892e42007-04-06 17:31:18 +00001660
Guido van Rossum8358db22007-08-18 21:39:55 +00001661 # In C we'd look for these in parallel of course.
1662 nlpos = line.find("\n", start)
1663 crpos = line.find("\r", start)
1664 if crpos == -1:
1665 if nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001666 # Nothing found
Guido van Rossum8358db22007-08-18 21:39:55 +00001667 start = len(line)
Guido van Rossum78892e42007-04-06 17:31:18 +00001668 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001669 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001670 endpos = nlpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001671 break
1672 elif nlpos == -1:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001673 # Found lone \r
1674 endpos = crpos + 1
1675 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001676 elif nlpos < crpos:
1677 # Found \n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001678 endpos = nlpos + 1
Guido van Rossum78892e42007-04-06 17:31:18 +00001679 break
Guido van Rossum8358db22007-08-18 21:39:55 +00001680 elif nlpos == crpos + 1:
1681 # Found \r\n
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001682 endpos = crpos + 2
Guido van Rossum8358db22007-08-18 21:39:55 +00001683 break
1684 else:
1685 # Found \r
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001686 endpos = crpos + 1
Guido van Rossum8358db22007-08-18 21:39:55 +00001687 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001688 else:
Guido van Rossum8358db22007-08-18 21:39:55 +00001689 # non-universal
1690 pos = line.find(self._readnl)
1691 if pos >= 0:
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001692 endpos = pos + len(self._readnl)
Guido van Rossum8358db22007-08-18 21:39:55 +00001693 break
Guido van Rossum78892e42007-04-06 17:31:18 +00001694
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001695 if limit >= 0 and len(line) >= limit:
1696 endpos = limit # reached length limit
1697 break
1698
Guido van Rossum78892e42007-04-06 17:31:18 +00001699 # No line ending seen yet - get more data
Guido van Rossum8358db22007-08-18 21:39:55 +00001700 more_line = ''
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001701 while self._read_chunk():
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001702 if self._decoded_chars:
Guido van Rossum78892e42007-04-06 17:31:18 +00001703 break
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001704 if self._decoded_chars:
1705 line += self._get_decoded_chars()
Guido van Rossum8358db22007-08-18 21:39:55 +00001706 else:
1707 # end of file
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001708 self._set_decoded_chars('')
1709 self._snapshot = None
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001710 return line
Guido van Rossum78892e42007-04-06 17:31:18 +00001711
Ka-Ping Yeedbe28e52008-03-20 10:34:07 +00001712 if limit >= 0 and endpos > limit:
1713 endpos = limit # don't exceed limit
1714
Ka-Ping Yee593cd6b2008-03-20 10:37:32 +00001715 # Rewind _decoded_chars to just after the line ending we found.
1716 self._rewind_decoded_chars(len(line) - endpos)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001717 return line[:endpos]
Guido van Rossum024da5c2007-05-17 23:59:11 +00001718
Guido van Rossum8358db22007-08-18 21:39:55 +00001719 @property
1720 def newlines(self):
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +00001721 return self._decoder.newlines if self._decoder else None
Guido van Rossum024da5c2007-05-17 23:59:11 +00001722
1723class StringIO(TextIOWrapper):
Benjamin Peterson2c5f8282008-04-13 00:27:46 +00001724 """StringIO([initial_value[, encoding, [errors, [newline]]]])
1725
1726 An in-memory stream for text. The initial_value argument sets the
1727 value of object. The other arguments are like those of TextIOWrapper's
1728 constructor.
1729 """
Guido van Rossum024da5c2007-05-17 23:59:11 +00001730
1731 # XXX This is really slow, but fully functional
1732
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001733 def __init__(self, initial_value="", encoding="utf-8",
1734 errors="strict", newline="\n"):
Guido van Rossum3e1f85e2007-07-27 18:03:11 +00001735 super(StringIO, self).__init__(BytesIO(),
1736 encoding=encoding,
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001737 errors=errors,
Guido van Rossum3e1f85e2007-07-27 18:03:11 +00001738 newline=newline)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001739 if initial_value:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001740 if not isinstance(initial_value, str):
Guido van Rossum34d19282007-08-09 01:03:29 +00001741 initial_value = str(initial_value)
Guido van Rossum024da5c2007-05-17 23:59:11 +00001742 self.write(initial_value)
1743 self.seek(0)
1744
1745 def getvalue(self):
Guido van Rossum34d19282007-08-09 01:03:29 +00001746 self.flush()
Guido van Rossume7fc50f2007-12-03 22:54:21 +00001747 return self.buffer.getvalue().decode(self._encoding, self._errors)