blob: af2ce30c27806234499c20d3df30e9b9db7f491d [file] [log] [blame]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001"""
2Python implementation of the io module.
3"""
4
5import os
6import abc
7import codecs
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01008import errno
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03009import stat
Serhiy Storchakaf0f55a02015-08-28 22:17:04 +030010import sys
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000011# Import _thread instead of threading to reduce startup cost
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020012from _thread import allocate_lock as Lock
Serhiy Storchakaf0f55a02015-08-28 22:17:04 +030013if sys.platform in {'win32', 'cygwin'}:
Serhiy Storchaka71fd2242015-04-10 16:16:16 +030014 from msvcrt import setmode as _setmode
15else:
16 _setmode = None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000017
18import io
Benjamin Petersonc3be11a2010-04-27 21:24:03 +000019from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000020
Jesus Cea94363612012-06-22 18:32:07 +020021valid_seek_flags = {0, 1, 2} # Hardwired values
22if hasattr(os, 'SEEK_HOLE') :
23 valid_seek_flags.add(os.SEEK_HOLE)
24 valid_seek_flags.add(os.SEEK_DATA)
25
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000026# open() uses st_blksize whenever we can
27DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
28
29# NOTE: Base classes defined here are registered with the "official" ABCs
Benjamin Peterson86fdbf32015-03-18 21:35:38 -050030# defined in io.py. We don't use real inheritance though, because we don't want
31# to inherit the C implementations.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000032
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020033# Rebind for compatibility
34BlockingIOError = BlockingIOError
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000035
36
Georg Brandl4d73b572011-01-13 07:13:06 +000037def open(file, mode="r", buffering=-1, encoding=None, errors=None,
Ross Lagerwall59142db2011-10-31 20:34:46 +020038 newline=None, closefd=True, opener=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000039
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020040 r"""Open file and return a stream. Raise OSError upon failure.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000041
42 file is either a text or byte string giving the name (and the path
43 if the file isn't in the current working directory) of the file to
44 be opened or an integer file descriptor of the file to be
45 wrapped. (If a file descriptor is given, it is closed when the
46 returned I/O object is closed, unless closefd is set to False.)
47
Charles-François Natalidc3044c2012-01-09 22:40:02 +010048 mode is an optional string that specifies the mode in which the file is
49 opened. It defaults to 'r' which means open for reading in text mode. Other
50 common values are 'w' for writing (truncating the file if it already
Charles-François Natalid612de12012-01-14 11:51:00 +010051 exists), 'x' for exclusive creation of a new file, and 'a' for appending
Charles-François Natalidc3044c2012-01-09 22:40:02 +010052 (which on some Unix systems, means that all writes append to the end of the
53 file regardless of the current seek position). In text mode, if encoding is
54 not specified the encoding used is platform dependent. (For reading and
55 writing raw bytes use binary mode and leave encoding unspecified.) The
56 available modes are:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000057
58 ========= ===============================================================
59 Character Meaning
60 --------- ---------------------------------------------------------------
61 'r' open for reading (default)
62 'w' open for writing, truncating the file first
Charles-François Natalidc3044c2012-01-09 22:40:02 +010063 'x' create a new file and open it for writing
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000064 'a' open for writing, appending to the end of the file if it exists
65 'b' binary mode
66 't' text mode (default)
67 '+' open a disk file for updating (reading and writing)
Serhiy Storchaka6787a382013-11-23 22:12:06 +020068 'U' universal newline mode (deprecated)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000069 ========= ===============================================================
70
71 The default mode is 'rt' (open for reading text). For binary random
72 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
Charles-François Natalidc3044c2012-01-09 22:40:02 +010073 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
74 raises an `FileExistsError` if the file already exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000075
76 Python distinguishes between files opened in binary and text modes,
77 even when the underlying operating system doesn't. Files opened in
78 binary mode (appending 'b' to the mode argument) return contents as
79 bytes objects without any decoding. In text mode (the default, or when
80 't' is appended to the mode argument), the contents of the file are
81 returned as strings, the bytes having been first decoded using a
82 platform-dependent encoding or using the specified encoding if given.
83
Serhiy Storchaka6787a382013-11-23 22:12:06 +020084 'U' mode is deprecated and will raise an exception in future versions
85 of Python. It has no effect in Python 3. Use newline to control
86 universal newlines mode.
87
Antoine Pitroud5587bc2009-12-19 21:08:31 +000088 buffering is an optional integer used to set the buffering policy.
89 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
90 line buffering (only usable in text mode), and an integer > 1 to indicate
91 the size of a fixed-size chunk buffer. When no buffering argument is
92 given, the default buffering policy works as follows:
93
94 * Binary files are buffered in fixed-size chunks; the size of the buffer
95 is chosen using a heuristic trying to determine the underlying device's
96 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
97 On many systems, the buffer will typically be 4096 or 8192 bytes long.
98
99 * "Interactive" text files (files for which isatty() returns True)
100 use line buffering. Other text files use the policy described above
101 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000102
Raymond Hettingercbb80892011-01-13 18:15:51 +0000103 encoding is the str name of the encoding used to decode or encode the
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000104 file. This should only be used in text mode. The default encoding is
105 platform dependent, but any encoding supported by Python can be
106 passed. See the codecs module for the list of supported encodings.
107
108 errors is an optional string that specifies how encoding errors are to
109 be handled---this argument should not be used in binary mode. Pass
110 'strict' to raise a ValueError exception if there is an encoding error
111 (the default of None has the same effect), or pass 'ignore' to ignore
112 errors. (Note that ignoring encoding errors can lead to data loss.)
113 See the documentation for codecs.register for a list of the permitted
114 encoding error strings.
115
Raymond Hettingercbb80892011-01-13 18:15:51 +0000116 newline is a string controlling how universal newlines works (it only
117 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
118 as follows:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000119
120 * On input, if newline is None, universal newlines mode is
121 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
122 these are translated into '\n' before being returned to the
123 caller. If it is '', universal newline mode is enabled, but line
124 endings are returned to the caller untranslated. If it has any of
125 the other legal values, input lines are only terminated by the given
126 string, and the line ending is returned to the caller untranslated.
127
128 * On output, if newline is None, any '\n' characters written are
129 translated to the system default line separator, os.linesep. If
130 newline is '', no translation takes place. If newline is any of the
131 other legal values, any '\n' characters written are translated to
132 the given string.
133
Raymond Hettingercbb80892011-01-13 18:15:51 +0000134 closedfd is a bool. If closefd is False, the underlying file descriptor will
135 be kept open when the file is closed. This does not work when a file name is
136 given and must be True in that case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000137
Victor Stinnerdaf45552013-08-28 00:53:59 +0200138 The newly created file is non-inheritable.
139
Ross Lagerwall59142db2011-10-31 20:34:46 +0200140 A custom opener can be used by passing a callable as *opener*. The
141 underlying file descriptor for the file object is then obtained by calling
142 *opener* with (*file*, *flags*). *opener* must return an open file
143 descriptor (passing os.open as *opener* results in functionality similar to
144 passing None).
145
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000146 open() returns a file object whose type depends on the mode, and
147 through which the standard file operations such as reading and writing
148 are performed. When open() is used to open a file in a text mode ('w',
149 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
150 a file in a binary mode, the returned class varies: in read binary
151 mode, it returns a BufferedReader; in write binary and append binary
152 modes, it returns a BufferedWriter, and in read/write mode, it returns
153 a BufferedRandom.
154
155 It is also possible to use a string or bytearray as a file for both
156 reading and writing. For strings StringIO can be used like a file
157 opened in a text mode, and for bytes a BytesIO can be used like a file
158 opened in a binary mode.
159 """
Ethan Furmand62548a2016-06-04 14:38:43 -0700160 if not isinstance(file, int):
161 file = os.fspath(file)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000162 if not isinstance(file, (str, bytes, int)):
163 raise TypeError("invalid file: %r" % file)
164 if not isinstance(mode, str):
165 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000166 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000167 raise TypeError("invalid buffering: %r" % buffering)
168 if encoding is not None and not isinstance(encoding, str):
169 raise TypeError("invalid encoding: %r" % encoding)
170 if errors is not None and not isinstance(errors, str):
171 raise TypeError("invalid errors: %r" % errors)
172 modes = set(mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100173 if modes - set("axrwb+tU") or len(mode) > len(modes):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000174 raise ValueError("invalid mode: %r" % mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100175 creating = "x" in modes
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000176 reading = "r" in modes
177 writing = "w" in modes
178 appending = "a" in modes
179 updating = "+" in modes
180 text = "t" in modes
181 binary = "b" in modes
182 if "U" in modes:
Robert Collinsc94a1dc2015-07-26 06:43:13 +1200183 if creating or writing or appending or updating:
184 raise ValueError("mode U cannot be combined with 'x', 'w', 'a', or '+'")
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200185 import warnings
186 warnings.warn("'U' mode is deprecated",
187 DeprecationWarning, 2)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000188 reading = True
189 if text and binary:
190 raise ValueError("can't have text and binary mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100191 if creating + reading + writing + appending > 1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000192 raise ValueError("can't have read/write/append mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100193 if not (creating or reading or writing or appending):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000194 raise ValueError("must have exactly one of read/write/append mode")
195 if binary and encoding is not None:
196 raise ValueError("binary mode doesn't take an encoding argument")
197 if binary and errors is not None:
198 raise ValueError("binary mode doesn't take an errors argument")
199 if binary and newline is not None:
200 raise ValueError("binary mode doesn't take a newline argument")
Alexey Izbysheva2670562018-10-20 03:22:31 +0300201 if binary and buffering == 1:
202 import warnings
203 warnings.warn("line buffering (buffering=1) isn't supported in binary "
204 "mode, the default buffer size will be used",
205 RuntimeWarning, 2)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000206 raw = FileIO(file,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100207 (creating and "x" or "") +
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000208 (reading and "r" or "") +
209 (writing and "w" or "") +
210 (appending and "a" or "") +
211 (updating and "+" or ""),
Ross Lagerwall59142db2011-10-31 20:34:46 +0200212 closefd, opener=opener)
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300213 result = raw
214 try:
215 line_buffering = False
216 if buffering == 1 or buffering < 0 and raw.isatty():
217 buffering = -1
218 line_buffering = True
219 if buffering < 0:
220 buffering = DEFAULT_BUFFER_SIZE
221 try:
222 bs = os.fstat(raw.fileno()).st_blksize
223 except (OSError, AttributeError):
224 pass
225 else:
226 if bs > 1:
227 buffering = bs
228 if buffering < 0:
229 raise ValueError("invalid buffering size")
230 if buffering == 0:
231 if binary:
232 return result
233 raise ValueError("can't have unbuffered text I/O")
234 if updating:
235 buffer = BufferedRandom(raw, buffering)
236 elif creating or writing or appending:
237 buffer = BufferedWriter(raw, buffering)
238 elif reading:
239 buffer = BufferedReader(raw, buffering)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000240 else:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300241 raise ValueError("unknown mode: %r" % mode)
242 result = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000243 if binary:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300244 return result
245 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
246 result = text
247 text.mode = mode
248 return result
249 except:
250 result.close()
251 raise
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000252
253
254class DocDescriptor:
255 """Helper for builtins.open.__doc__
256 """
257 def __get__(self, obj, typ):
258 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000259 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000260 "errors=None, newline=None, closefd=True)\n\n" +
261 open.__doc__)
262
263class OpenWrapper:
264 """Wrapper for builtins.open
265
266 Trick so that open won't become a bound method when stored
267 as a class variable (as dbm.dumb does).
268
Nick Coghland6009512014-11-20 21:39:37 +1000269 See initstdio() in Python/pylifecycle.c.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000270 """
271 __doc__ = DocDescriptor()
272
273 def __new__(cls, *args, **kwargs):
274 return open(*args, **kwargs)
275
276
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000277# In normal operation, both `UnsupportedOperation`s should be bound to the
278# same object.
279try:
280 UnsupportedOperation = io.UnsupportedOperation
281except AttributeError:
Serhiy Storchaka606ab862016-12-07 13:31:20 +0200282 class UnsupportedOperation(OSError, ValueError):
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000283 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000284
285
286class IOBase(metaclass=abc.ABCMeta):
287
288 """The abstract base class for all I/O classes, acting on streams of
289 bytes. There is no public constructor.
290
291 This class provides dummy implementations for many methods that
292 derived classes can override selectively; the default implementations
293 represent a file that cannot be read, written or seeked.
294
Steve Palmer7b97ab32019-04-09 05:35:27 +0100295 Even though IOBase does not declare read or write because
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000296 their signatures will vary, implementations and clients should
297 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000298 may raise UnsupportedOperation when operations they do not support are
299 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000300
301 The basic type used for binary data read from or written to a file is
Steve Palmer7b97ab32019-04-09 05:35:27 +0100302 bytes. Other bytes-like objects are accepted as method arguments too.
303 Text I/O classes work with str data.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000304
305 Note that calling any method (even inquiries) on a closed stream is
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200306 undefined. Implementations may raise OSError in this case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000307
308 IOBase (and its subclasses) support the iterator protocol, meaning
309 that an IOBase object can be iterated over yielding the lines in a
310 stream.
311
312 IOBase also supports the :keyword:`with` statement. In this example,
313 fp is closed after the suite of the with statement is complete:
314
315 with open('spam.txt', 'r') as fp:
316 fp.write('Spam and eggs!')
317 """
318
319 ### Internal ###
320
Raymond Hettinger3c940242011-01-12 23:39:31 +0000321 def _unsupported(self, name):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200322 """Internal: raise an OSError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000323 raise UnsupportedOperation("%s.%s() not supported" %
324 (self.__class__.__name__, name))
325
326 ### Positioning ###
327
Georg Brandl4d73b572011-01-13 07:13:06 +0000328 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000329 """Change stream position.
330
Terry Jan Reedyc30b7b12013-03-11 17:57:08 -0400331 Change the stream position to byte offset pos. Argument pos is
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000332 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000333 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000334
335 * 0 -- start of stream (the default); offset should be zero or positive
336 * 1 -- current stream position; offset may be negative
337 * 2 -- end of stream; offset is usually negative
Jesus Cea94363612012-06-22 18:32:07 +0200338 Some operating systems / file systems could provide additional values.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000339
Raymond Hettingercbb80892011-01-13 18:15:51 +0000340 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000341 """
342 self._unsupported("seek")
343
Raymond Hettinger3c940242011-01-12 23:39:31 +0000344 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000345 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000346 return self.seek(0, 1)
347
Georg Brandl4d73b572011-01-13 07:13:06 +0000348 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000349 """Truncate file to size bytes.
350
351 Size defaults to the current IO position as reported by tell(). Return
352 the new size.
353 """
354 self._unsupported("truncate")
355
356 ### Flush and close ###
357
Raymond Hettinger3c940242011-01-12 23:39:31 +0000358 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000359 """Flush write buffers, if applicable.
360
361 This is not implemented for read-only and non-blocking streams.
362 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000363 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000364 # XXX Should this return the number of bytes written???
365
366 __closed = False
367
Raymond Hettinger3c940242011-01-12 23:39:31 +0000368 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000369 """Flush and close the IO object.
370
371 This method has no effect if the file is already closed.
372 """
373 if not self.__closed:
Benjamin Peterson68623612012-12-20 11:53:11 -0600374 try:
375 self.flush()
376 finally:
377 self.__closed = True
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000378
Raymond Hettinger3c940242011-01-12 23:39:31 +0000379 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000380 """Destructor. Calls close()."""
381 # The try/except block is in case this is called at program
382 # exit time, when it's possible that globals have already been
383 # deleted, and then the close() call might fail. Since
384 # there's nothing we can do about such failures and they annoy
385 # the end users, we suppress the traceback.
386 try:
387 self.close()
388 except:
389 pass
390
391 ### Inquiries ###
392
Raymond Hettinger3c940242011-01-12 23:39:31 +0000393 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000394 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000395
Martin Panter754aab22016-03-31 07:21:56 +0000396 If False, seek(), tell() and truncate() will raise OSError.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000397 This method may need to do a test seek().
398 """
399 return False
400
401 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000402 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000403 """
404 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000405 raise UnsupportedOperation("File or stream is not seekable."
406 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000407
Raymond Hettinger3c940242011-01-12 23:39:31 +0000408 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000409 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000410
Martin Panter754aab22016-03-31 07:21:56 +0000411 If False, read() will raise OSError.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000412 """
413 return False
414
415 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000416 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000417 """
418 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000419 raise UnsupportedOperation("File or stream is not readable."
420 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000421
Raymond Hettinger3c940242011-01-12 23:39:31 +0000422 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000423 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000424
Martin Panter754aab22016-03-31 07:21:56 +0000425 If False, write() and truncate() will raise OSError.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000426 """
427 return False
428
429 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000430 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000431 """
432 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000433 raise UnsupportedOperation("File or stream is not writable."
434 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000435
436 @property
437 def closed(self):
438 """closed: bool. True iff the file has been closed.
439
440 For backwards compatibility, this is a property, not a predicate.
441 """
442 return self.__closed
443
444 def _checkClosed(self, msg=None):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300445 """Internal: raise a ValueError if file is closed
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000446 """
447 if self.closed:
448 raise ValueError("I/O operation on closed file."
449 if msg is None else msg)
450
451 ### Context manager ###
452
Raymond Hettinger3c940242011-01-12 23:39:31 +0000453 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000454 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000455 self._checkClosed()
456 return self
457
Raymond Hettinger3c940242011-01-12 23:39:31 +0000458 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000459 """Context management protocol. Calls close()"""
460 self.close()
461
462 ### Lower-level APIs ###
463
464 # XXX Should these be present even if unimplemented?
465
Raymond Hettinger3c940242011-01-12 23:39:31 +0000466 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000467 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000468
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200469 An OSError is raised if the IO object does not use a file descriptor.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000470 """
471 self._unsupported("fileno")
472
Raymond Hettinger3c940242011-01-12 23:39:31 +0000473 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000474 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000475
476 Return False if it can't be determined.
477 """
478 self._checkClosed()
479 return False
480
481 ### Readline[s] and writelines ###
482
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300483 def readline(self, size=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000484 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000485
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300486 If size is specified, at most size bytes will be read.
487 Size should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000488
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().
494 if hasattr(self, "peek"):
495 def nreadahead():
496 readahead = self.peek(1)
497 if not readahead:
498 return 1
499 n = (readahead.find(b"\n") + 1) or len(readahead)
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300500 if size >= 0:
501 n = min(n, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000502 return n
503 else:
504 def nreadahead():
505 return 1
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300506 if size is None:
507 size = -1
Oren Milmande503602017-08-24 21:33:42 +0300508 else:
509 try:
510 size_index = size.__index__
511 except AttributeError:
512 raise TypeError(f"{size!r} is not an integer")
513 else:
514 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000515 res = bytearray()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300516 while size < 0 or len(res) < size:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000517 b = self.read(nreadahead())
518 if not b:
519 break
520 res += b
521 if res.endswith(b"\n"):
522 break
523 return bytes(res)
524
525 def __iter__(self):
526 self._checkClosed()
527 return self
528
529 def __next__(self):
530 line = self.readline()
531 if not line:
532 raise StopIteration
533 return line
534
535 def readlines(self, hint=None):
536 """Return a list of lines from the stream.
537
538 hint can be specified to control the number of lines read: no more
539 lines will be read if the total size (in bytes/characters) of all
540 lines so far exceeds hint.
541 """
542 if hint is None or hint <= 0:
543 return list(self)
544 n = 0
545 lines = []
546 for line in self:
547 lines.append(line)
548 n += len(line)
549 if n >= hint:
550 break
551 return lines
552
553 def writelines(self, lines):
Marcin Niemiraab865212019-04-22 21:13:51 +1000554 """Write a list of lines to the stream.
555
556 Line separators are not added, so it is usual for each of the lines
557 provided to have a line separator at the end.
558 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000559 self._checkClosed()
560 for line in lines:
561 self.write(line)
562
563io.IOBase.register(IOBase)
564
565
566class RawIOBase(IOBase):
567
568 """Base class for raw binary I/O."""
569
570 # The read() method is implemented by calling readinto(); derived
571 # classes that want to support read() only need to implement
572 # readinto() as a primitive operation. In general, readinto() can be
573 # more efficient than read().
574
575 # (It would be tempting to also provide an implementation of
576 # readinto() in terms of read(), in case the latter is a more suitable
577 # primitive operation, but that would lead to nasty recursion in case
578 # a subclass doesn't implement either.)
579
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300580 def read(self, size=-1):
581 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000582
583 Returns an empty bytes object on EOF, or None if the object is
584 set not to block and has no data to read.
585 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300586 if size is None:
587 size = -1
588 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000589 return self.readall()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300590 b = bytearray(size.__index__())
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000591 n = self.readinto(b)
Antoine Pitrou328ec742010-09-14 18:37:24 +0000592 if n is None:
593 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000594 del b[n:]
595 return bytes(b)
596
597 def readall(self):
598 """Read until EOF, using multiple read() call."""
599 res = bytearray()
600 while True:
601 data = self.read(DEFAULT_BUFFER_SIZE)
602 if not data:
603 break
604 res += data
Victor Stinnera80987f2011-05-25 22:47:16 +0200605 if res:
606 return bytes(res)
607 else:
608 # b'' or None
609 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000610
Raymond Hettinger3c940242011-01-12 23:39:31 +0000611 def readinto(self, b):
Martin Panter6bb91f32016-05-28 00:41:57 +0000612 """Read bytes into a pre-allocated bytes-like object b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000613
Raymond Hettingercbb80892011-01-13 18:15:51 +0000614 Returns an int representing the number of bytes read (0 for EOF), or
615 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000616 """
617 self._unsupported("readinto")
618
Raymond Hettinger3c940242011-01-12 23:39:31 +0000619 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000620 """Write the given buffer to the IO stream.
621
Martin Panter6bb91f32016-05-28 00:41:57 +0000622 Returns the number of bytes written, which may be less than the
623 length of b in bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000624 """
625 self._unsupported("write")
626
627io.RawIOBase.register(RawIOBase)
628from _io import FileIO
629RawIOBase.register(FileIO)
630
631
632class BufferedIOBase(IOBase):
633
634 """Base class for buffered IO objects.
635
636 The main difference with RawIOBase is that the read() method
637 supports omitting the size argument, and does not have a default
638 implementation that defers to readinto().
639
640 In addition, read(), readinto() and write() may raise
641 BlockingIOError if the underlying raw stream is in non-blocking
642 mode and not ready; unlike their raw counterparts, they will never
643 return None.
644
645 A typical implementation should not inherit from a RawIOBase
646 implementation, but wrap one.
647 """
648
Martin Panterccb2c0e2016-10-20 23:48:14 +0000649 def read(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300650 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000651
652 If the argument is omitted, None, or negative, reads and
653 returns all data until EOF.
654
655 If the argument is positive, and the underlying raw stream is
656 not 'interactive', multiple raw reads may be issued to satisfy
657 the byte count (unless EOF is reached first). But for
658 interactive raw streams (XXX and for pipes?), at most one raw
659 read will be issued, and a short result does not imply that
660 EOF is imminent.
661
662 Returns an empty bytes array on EOF.
663
664 Raises BlockingIOError if the underlying raw stream has no
665 data at the moment.
666 """
667 self._unsupported("read")
668
Martin Panterccb2c0e2016-10-20 23:48:14 +0000669 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300670 """Read up to size bytes with at most one read() system call,
671 where size is an int.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000672 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000673 self._unsupported("read1")
674
Raymond Hettinger3c940242011-01-12 23:39:31 +0000675 def readinto(self, b):
Martin Panter6bb91f32016-05-28 00:41:57 +0000676 """Read bytes into a pre-allocated bytes-like object b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000677
678 Like read(), this may issue multiple reads to the underlying raw
679 stream, unless the latter is 'interactive'.
680
Raymond Hettingercbb80892011-01-13 18:15:51 +0000681 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000682
683 Raises BlockingIOError if the underlying raw stream has no
684 data at the moment.
685 """
Benjamin Petersona96fea02014-06-22 14:17:44 -0700686
687 return self._readinto(b, read1=False)
688
689 def readinto1(self, b):
Martin Panter6bb91f32016-05-28 00:41:57 +0000690 """Read bytes into buffer *b*, using at most one system call
Benjamin Petersona96fea02014-06-22 14:17:44 -0700691
692 Returns an int representing the number of bytes read (0 for EOF).
693
694 Raises BlockingIOError if the underlying raw stream has no
695 data at the moment.
696 """
697
698 return self._readinto(b, read1=True)
699
700 def _readinto(self, b, read1):
701 if not isinstance(b, memoryview):
702 b = memoryview(b)
703 b = b.cast('B')
704
705 if read1:
706 data = self.read1(len(b))
707 else:
708 data = self.read(len(b))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000709 n = len(data)
Benjamin Petersona96fea02014-06-22 14:17:44 -0700710
711 b[:n] = data
712
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000713 return n
714
Raymond Hettinger3c940242011-01-12 23:39:31 +0000715 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000716 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000717
Martin Panter6bb91f32016-05-28 00:41:57 +0000718 Return the number of bytes written, which is always the length of b
719 in bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000720
721 Raises BlockingIOError if the buffer is full and the
722 underlying raw stream cannot accept more data at the moment.
723 """
724 self._unsupported("write")
725
Raymond Hettinger3c940242011-01-12 23:39:31 +0000726 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000727 """
728 Separate the underlying raw stream from the buffer and return it.
729
730 After the raw stream has been detached, the buffer is in an unusable
731 state.
732 """
733 self._unsupported("detach")
734
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000735io.BufferedIOBase.register(BufferedIOBase)
736
737
738class _BufferedIOMixin(BufferedIOBase):
739
740 """A mixin implementation of BufferedIOBase with an underlying raw stream.
741
742 This passes most requests on to the underlying raw stream. It
743 does *not* provide implementations of read(), readinto() or
744 write().
745 """
746
747 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000748 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000749
750 ### Positioning ###
751
752 def seek(self, pos, whence=0):
753 new_position = self.raw.seek(pos, whence)
754 if new_position < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200755 raise OSError("seek() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000756 return new_position
757
758 def tell(self):
759 pos = self.raw.tell()
760 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200761 raise OSError("tell() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000762 return pos
763
764 def truncate(self, pos=None):
765 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
766 # and a flush may be necessary to synch both views of the current
767 # file state.
768 self.flush()
769
770 if pos is None:
771 pos = self.tell()
772 # XXX: Should seek() be used, instead of passing the position
773 # XXX directly to truncate?
774 return self.raw.truncate(pos)
775
776 ### Flush and close ###
777
778 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000779 if self.closed:
Jim Fasarakis-Hilliard1e73dbb2017-03-26 23:59:08 +0300780 raise ValueError("flush on closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000781 self.raw.flush()
782
783 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000784 if self.raw is not None and not self.closed:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +0100785 try:
786 # may raise BlockingIOError or BrokenPipeError etc
787 self.flush()
788 finally:
789 self.raw.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000790
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000791 def detach(self):
792 if self.raw is None:
793 raise ValueError("raw stream already detached")
794 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000795 raw = self._raw
796 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000797 return raw
798
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000799 ### Inquiries ###
800
801 def seekable(self):
802 return self.raw.seekable()
803
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000804 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000805 def raw(self):
806 return self._raw
807
808 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000809 def closed(self):
810 return self.raw.closed
811
812 @property
813 def name(self):
814 return self.raw.name
815
816 @property
817 def mode(self):
818 return self.raw.mode
819
Antoine Pitrou243757e2010-11-05 21:15:39 +0000820 def __getstate__(self):
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +0200821 raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
Antoine Pitrou243757e2010-11-05 21:15:39 +0000822
Antoine Pitrou716c4442009-05-23 19:04:03 +0000823 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300824 modname = self.__class__.__module__
825 clsname = self.__class__.__qualname__
Antoine Pitrou716c4442009-05-23 19:04:03 +0000826 try:
827 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -0600828 except Exception:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300829 return "<{}.{}>".format(modname, clsname)
Antoine Pitrou716c4442009-05-23 19:04:03 +0000830 else:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300831 return "<{}.{} name={!r}>".format(modname, clsname, name)
Antoine Pitrou716c4442009-05-23 19:04:03 +0000832
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000833 ### Lower-level APIs ###
834
835 def fileno(self):
836 return self.raw.fileno()
837
838 def isatty(self):
839 return self.raw.isatty()
840
841
842class BytesIO(BufferedIOBase):
843
844 """Buffered I/O implementation using an in-memory bytes buffer."""
845
846 def __init__(self, initial_bytes=None):
847 buf = bytearray()
848 if initial_bytes is not None:
849 buf += initial_bytes
850 self._buffer = buf
851 self._pos = 0
852
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000853 def __getstate__(self):
854 if self.closed:
855 raise ValueError("__getstate__ on closed file")
856 return self.__dict__.copy()
857
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000858 def getvalue(self):
859 """Return the bytes value (contents) of the buffer
860 """
861 if self.closed:
862 raise ValueError("getvalue on closed file")
863 return bytes(self._buffer)
864
Antoine Pitrou972ee132010-09-06 18:48:21 +0000865 def getbuffer(self):
866 """Return a readable and writable view of the buffer.
867 """
Serhiy Storchakac057c382015-02-03 02:00:18 +0200868 if self.closed:
869 raise ValueError("getbuffer on closed file")
Antoine Pitrou972ee132010-09-06 18:48:21 +0000870 return memoryview(self._buffer)
871
Serhiy Storchakac057c382015-02-03 02:00:18 +0200872 def close(self):
873 self._buffer.clear()
874 super().close()
875
Martin Panterccb2c0e2016-10-20 23:48:14 +0000876 def read(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000877 if self.closed:
878 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300879 if size is None:
880 size = -1
Oren Milmande503602017-08-24 21:33:42 +0300881 else:
882 try:
883 size_index = size.__index__
884 except AttributeError:
885 raise TypeError(f"{size!r} is not an integer")
886 else:
887 size = size_index()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300888 if size < 0:
889 size = len(self._buffer)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000890 if len(self._buffer) <= self._pos:
891 return b""
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300892 newpos = min(len(self._buffer), self._pos + size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000893 b = self._buffer[self._pos : newpos]
894 self._pos = newpos
895 return bytes(b)
896
Martin Panterccb2c0e2016-10-20 23:48:14 +0000897 def read1(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000898 """This is the same as read.
899 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300900 return self.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000901
902 def write(self, b):
903 if self.closed:
904 raise ValueError("write to closed file")
905 if isinstance(b, str):
906 raise TypeError("can't write str to binary stream")
Martin Panter6bb91f32016-05-28 00:41:57 +0000907 with memoryview(b) as view:
908 n = view.nbytes # Size of any bytes-like object
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000909 if n == 0:
910 return 0
911 pos = self._pos
912 if pos > len(self._buffer):
913 # Inserts null bytes between the current end of the file
914 # and the new write position.
915 padding = b'\x00' * (pos - len(self._buffer))
916 self._buffer += padding
917 self._buffer[pos:pos + n] = b
918 self._pos += n
919 return n
920
921 def seek(self, pos, whence=0):
922 if self.closed:
923 raise ValueError("seek on closed file")
924 try:
Oren Milmande503602017-08-24 21:33:42 +0300925 pos_index = pos.__index__
926 except AttributeError:
927 raise TypeError(f"{pos!r} is not an integer")
928 else:
929 pos = pos_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000930 if whence == 0:
931 if pos < 0:
932 raise ValueError("negative seek position %r" % (pos,))
933 self._pos = pos
934 elif whence == 1:
935 self._pos = max(0, self._pos + pos)
936 elif whence == 2:
937 self._pos = max(0, len(self._buffer) + pos)
938 else:
Jesus Cea94363612012-06-22 18:32:07 +0200939 raise ValueError("unsupported whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000940 return self._pos
941
942 def tell(self):
943 if self.closed:
944 raise ValueError("tell on closed file")
945 return self._pos
946
947 def truncate(self, pos=None):
948 if self.closed:
949 raise ValueError("truncate on closed file")
950 if pos is None:
951 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000952 else:
953 try:
Oren Milmande503602017-08-24 21:33:42 +0300954 pos_index = pos.__index__
955 except AttributeError:
956 raise TypeError(f"{pos!r} is not an integer")
957 else:
958 pos = pos_index()
Florent Xiclunab14930c2010-03-13 15:26:44 +0000959 if pos < 0:
960 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000961 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000962 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000963
964 def readable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200965 if self.closed:
966 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000967 return True
968
969 def writable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200970 if self.closed:
971 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000972 return True
973
974 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200975 if self.closed:
976 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000977 return True
978
979
980class BufferedReader(_BufferedIOMixin):
981
982 """BufferedReader(raw[, buffer_size])
983
984 A buffer for a readable, sequential BaseRawIO object.
985
986 The constructor creates a BufferedReader for the given readable raw
987 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
988 is used.
989 """
990
991 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
992 """Create a new buffered reader using the given readable raw IO object.
993 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000994 if not raw.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200995 raise OSError('"raw" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000996
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000997 _BufferedIOMixin.__init__(self, raw)
998 if buffer_size <= 0:
999 raise ValueError("invalid buffer size")
1000 self.buffer_size = buffer_size
1001 self._reset_read_buf()
1002 self._read_lock = Lock()
1003
Martin Panter754aab22016-03-31 07:21:56 +00001004 def readable(self):
1005 return self.raw.readable()
1006
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001007 def _reset_read_buf(self):
1008 self._read_buf = b""
1009 self._read_pos = 0
1010
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001011 def read(self, size=None):
1012 """Read size bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001013
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001014 Returns exactly size bytes of data unless the underlying raw IO
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001015 stream reaches EOF or if the call would block in non-blocking
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001016 mode. If size is negative, read until EOF or until read() would
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001017 block.
1018 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001019 if size is not None and size < -1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001020 raise ValueError("invalid number of bytes to read")
1021 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001022 return self._read_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001023
1024 def _read_unlocked(self, n=None):
1025 nodata_val = b""
1026 empty_values = (b"", None)
1027 buf = self._read_buf
1028 pos = self._read_pos
1029
1030 # Special case for when the number of bytes to read is unspecified.
1031 if n is None or n == -1:
1032 self._reset_read_buf()
Victor Stinnerb57f1082011-05-26 00:19:38 +02001033 if hasattr(self.raw, 'readall'):
1034 chunk = self.raw.readall()
1035 if chunk is None:
1036 return buf[pos:] or None
1037 else:
1038 return buf[pos:] + chunk
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001039 chunks = [buf[pos:]] # Strip the consumed bytes.
1040 current_size = 0
1041 while True:
1042 # Read until EOF or until read() would block.
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001043 chunk = self.raw.read()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001044 if chunk in empty_values:
1045 nodata_val = chunk
1046 break
1047 current_size += len(chunk)
1048 chunks.append(chunk)
1049 return b"".join(chunks) or nodata_val
1050
1051 # The number of bytes to read is specified, return at most n bytes.
1052 avail = len(buf) - pos # Length of the available buffered data.
1053 if n <= avail:
1054 # Fast path: the data to read is fully buffered.
1055 self._read_pos += n
1056 return buf[pos:pos+n]
1057 # Slow path: read from the stream until enough bytes are read,
1058 # or until an EOF occurs or until read() would block.
1059 chunks = [buf[pos:]]
1060 wanted = max(self.buffer_size, n)
1061 while avail < n:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001062 chunk = self.raw.read(wanted)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001063 if chunk in empty_values:
1064 nodata_val = chunk
1065 break
1066 avail += len(chunk)
1067 chunks.append(chunk)
Martin Pantere26da7c2016-06-02 10:07:09 +00001068 # n is more than avail only when an EOF occurred or when
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001069 # read() would have blocked.
1070 n = min(n, avail)
1071 out = b"".join(chunks)
1072 self._read_buf = out[n:] # Save the extra data in the buffer.
1073 self._read_pos = 0
1074 return out[:n] if out else nodata_val
1075
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001076 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001077 """Returns buffered bytes without advancing the position.
1078
1079 The argument indicates a desired minimal number of bytes; we
1080 do at most one raw read to satisfy it. We never return more
1081 than self.buffer_size.
1082 """
1083 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001084 return self._peek_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001085
1086 def _peek_unlocked(self, n=0):
1087 want = min(n, self.buffer_size)
1088 have = len(self._read_buf) - self._read_pos
1089 if have < want or have <= 0:
1090 to_read = self.buffer_size - have
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001091 current = self.raw.read(to_read)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001092 if current:
1093 self._read_buf = self._read_buf[self._read_pos:] + current
1094 self._read_pos = 0
1095 return self._read_buf[self._read_pos:]
1096
Martin Panterccb2c0e2016-10-20 23:48:14 +00001097 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001098 """Reads up to size bytes, with at most one read() system call."""
1099 # Returns up to size bytes. If at least one byte is buffered, we
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001100 # only return buffered bytes. Otherwise, we do one raw read.
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001101 if size < 0:
Martin Panterccb2c0e2016-10-20 23:48:14 +00001102 size = self.buffer_size
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001103 if size == 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001104 return b""
1105 with self._read_lock:
1106 self._peek_unlocked(1)
1107 return self._read_unlocked(
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001108 min(size, len(self._read_buf) - self._read_pos))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001109
Benjamin Petersona96fea02014-06-22 14:17:44 -07001110 # Implementing readinto() and readinto1() is not strictly necessary (we
1111 # could rely on the base class that provides an implementation in terms of
1112 # read() and read1()). We do it anyway to keep the _pyio implementation
1113 # similar to the io implementation (which implements the methods for
1114 # performance reasons).
1115 def _readinto(self, buf, read1):
1116 """Read data into *buf* with at most one system call."""
1117
Benjamin Petersona96fea02014-06-22 14:17:44 -07001118 # Need to create a memoryview object of type 'b', otherwise
1119 # we may not be able to assign bytes to it, and slicing it
1120 # would create a new object.
1121 if not isinstance(buf, memoryview):
1122 buf = memoryview(buf)
Martin Panter6bb91f32016-05-28 00:41:57 +00001123 if buf.nbytes == 0:
1124 return 0
Benjamin Petersona96fea02014-06-22 14:17:44 -07001125 buf = buf.cast('B')
1126
1127 written = 0
1128 with self._read_lock:
1129 while written < len(buf):
1130
1131 # First try to read from internal buffer
1132 avail = min(len(self._read_buf) - self._read_pos, len(buf))
1133 if avail:
1134 buf[written:written+avail] = \
1135 self._read_buf[self._read_pos:self._read_pos+avail]
1136 self._read_pos += avail
1137 written += avail
1138 if written == len(buf):
1139 break
1140
1141 # If remaining space in callers buffer is larger than
1142 # internal buffer, read directly into callers buffer
1143 if len(buf) - written > self.buffer_size:
1144 n = self.raw.readinto(buf[written:])
1145 if not n:
1146 break # eof
1147 written += n
1148
1149 # Otherwise refill internal buffer - unless we're
1150 # in read1 mode and already got some data
1151 elif not (read1 and written):
1152 if not self._peek_unlocked(1):
1153 break # eof
1154
1155 # In readinto1 mode, return as soon as we have some data
1156 if read1 and written:
1157 break
1158
1159 return written
1160
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001161 def tell(self):
1162 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1163
1164 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001165 if whence not in valid_seek_flags:
Jesus Cea990eff02012-04-26 17:05:31 +02001166 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001167 with self._read_lock:
1168 if whence == 1:
1169 pos -= len(self._read_buf) - self._read_pos
1170 pos = _BufferedIOMixin.seek(self, pos, whence)
1171 self._reset_read_buf()
1172 return pos
1173
1174class BufferedWriter(_BufferedIOMixin):
1175
1176 """A buffer for a writeable sequential RawIO object.
1177
1178 The constructor creates a BufferedWriter for the given writeable raw
1179 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001180 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001181 """
1182
Florent Xicluna109d5732012-07-07 17:03:22 +02001183 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001184 if not raw.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001185 raise OSError('"raw" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001186
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001187 _BufferedIOMixin.__init__(self, raw)
1188 if buffer_size <= 0:
1189 raise ValueError("invalid buffer size")
1190 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001191 self._write_buf = bytearray()
1192 self._write_lock = Lock()
1193
Martin Panter754aab22016-03-31 07:21:56 +00001194 def writable(self):
1195 return self.raw.writable()
1196
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001197 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001198 if isinstance(b, str):
1199 raise TypeError("can't write str to binary stream")
1200 with self._write_lock:
benfogle9703f092017-11-10 16:03:40 -05001201 if self.closed:
1202 raise ValueError("write to closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001203 # XXX we can implement some more tricks to try and avoid
1204 # partial writes
1205 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001206 # We're full, so let's pre-flush the buffer. (This may
1207 # raise BlockingIOError with characters_written == 0.)
1208 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001209 before = len(self._write_buf)
1210 self._write_buf.extend(b)
1211 written = len(self._write_buf) - before
1212 if len(self._write_buf) > self.buffer_size:
1213 try:
1214 self._flush_unlocked()
1215 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001216 if len(self._write_buf) > self.buffer_size:
1217 # We've hit the buffer_size. We have to accept a partial
1218 # write and cut back our buffer.
1219 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001220 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001221 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001222 raise BlockingIOError(e.errno, e.strerror, written)
1223 return written
1224
1225 def truncate(self, pos=None):
1226 with self._write_lock:
1227 self._flush_unlocked()
1228 if pos is None:
1229 pos = self.raw.tell()
1230 return self.raw.truncate(pos)
1231
1232 def flush(self):
1233 with self._write_lock:
1234 self._flush_unlocked()
1235
1236 def _flush_unlocked(self):
1237 if self.closed:
Jim Fasarakis-Hilliard1e73dbb2017-03-26 23:59:08 +03001238 raise ValueError("flush on closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001239 while self._write_buf:
1240 try:
1241 n = self.raw.write(self._write_buf)
1242 except BlockingIOError:
1243 raise RuntimeError("self.raw should implement RawIOBase: it "
1244 "should not raise BlockingIOError")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001245 if n is None:
1246 raise BlockingIOError(
1247 errno.EAGAIN,
1248 "write could not complete without blocking", 0)
1249 if n > len(self._write_buf) or n < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001250 raise OSError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001251 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001252
1253 def tell(self):
1254 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1255
1256 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001257 if whence not in valid_seek_flags:
1258 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001259 with self._write_lock:
1260 self._flush_unlocked()
1261 return _BufferedIOMixin.seek(self, pos, whence)
1262
benfogle9703f092017-11-10 16:03:40 -05001263 def close(self):
1264 with self._write_lock:
1265 if self.raw is None or self.closed:
1266 return
1267 # We have to release the lock and call self.flush() (which will
1268 # probably just re-take the lock) in case flush has been overridden in
1269 # a subclass or the user set self.flush to something. This is the same
1270 # behavior as the C implementation.
1271 try:
1272 # may raise BlockingIOError or BrokenPipeError etc
1273 self.flush()
1274 finally:
1275 with self._write_lock:
1276 self.raw.close()
1277
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001278
1279class BufferedRWPair(BufferedIOBase):
1280
1281 """A buffered reader and writer object together.
1282
1283 A buffered reader object and buffered writer object put together to
1284 form a sequential IO object that can read and write. This is typically
1285 used with a socket or two-way pipe.
1286
1287 reader and writer are RawIOBase objects that are readable and
1288 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001289 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001290 """
1291
1292 # XXX The usefulness of this (compared to having two separate IO
1293 # objects) is questionable.
1294
Florent Xicluna109d5732012-07-07 17:03:22 +02001295 def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001296 """Constructor.
1297
1298 The arguments are two RawIO instances.
1299 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001300 if not reader.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001301 raise OSError('"reader" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001302
1303 if not writer.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001304 raise OSError('"writer" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001305
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001306 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001307 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001308
Martin Panterccb2c0e2016-10-20 23:48:14 +00001309 def read(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001310 if size is None:
1311 size = -1
1312 return self.reader.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001313
1314 def readinto(self, b):
1315 return self.reader.readinto(b)
1316
1317 def write(self, b):
1318 return self.writer.write(b)
1319
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001320 def peek(self, size=0):
1321 return self.reader.peek(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001322
Martin Panterccb2c0e2016-10-20 23:48:14 +00001323 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001324 return self.reader.read1(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001325
Benjamin Petersona96fea02014-06-22 14:17:44 -07001326 def readinto1(self, b):
1327 return self.reader.readinto1(b)
1328
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001329 def readable(self):
1330 return self.reader.readable()
1331
1332 def writable(self):
1333 return self.writer.writable()
1334
1335 def flush(self):
1336 return self.writer.flush()
1337
1338 def close(self):
Serhiy Storchaka7665be62015-03-24 23:21:57 +02001339 try:
1340 self.writer.close()
1341 finally:
1342 self.reader.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001343
1344 def isatty(self):
1345 return self.reader.isatty() or self.writer.isatty()
1346
1347 @property
1348 def closed(self):
1349 return self.writer.closed
1350
1351
1352class BufferedRandom(BufferedWriter, BufferedReader):
1353
1354 """A buffered interface to random access streams.
1355
1356 The constructor creates a reader and writer for a seekable stream,
1357 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001358 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001359 """
1360
Florent Xicluna109d5732012-07-07 17:03:22 +02001361 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001362 raw._checkSeekable()
1363 BufferedReader.__init__(self, raw, buffer_size)
Florent Xicluna109d5732012-07-07 17:03:22 +02001364 BufferedWriter.__init__(self, raw, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001365
1366 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001367 if whence not in valid_seek_flags:
1368 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001369 self.flush()
1370 if self._read_buf:
1371 # Undo read ahead.
1372 with self._read_lock:
1373 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1374 # First do the raw seek, then empty the read buffer, so that
1375 # if the raw seek fails, we don't lose buffered data forever.
1376 pos = self.raw.seek(pos, whence)
1377 with self._read_lock:
1378 self._reset_read_buf()
1379 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001380 raise OSError("seek() returned invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001381 return pos
1382
1383 def tell(self):
1384 if self._write_buf:
1385 return BufferedWriter.tell(self)
1386 else:
1387 return BufferedReader.tell(self)
1388
1389 def truncate(self, pos=None):
1390 if pos is None:
1391 pos = self.tell()
1392 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001393 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001394
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001395 def read(self, size=None):
1396 if size is None:
1397 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001398 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001399 return BufferedReader.read(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001400
1401 def readinto(self, b):
1402 self.flush()
1403 return BufferedReader.readinto(self, b)
1404
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001405 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001406 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001407 return BufferedReader.peek(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001408
Martin Panterccb2c0e2016-10-20 23:48:14 +00001409 def read1(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001410 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001411 return BufferedReader.read1(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001412
Benjamin Petersona96fea02014-06-22 14:17:44 -07001413 def readinto1(self, b):
1414 self.flush()
1415 return BufferedReader.readinto1(self, b)
1416
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001417 def write(self, b):
1418 if self._read_buf:
1419 # Undo readahead
1420 with self._read_lock:
1421 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1422 self._reset_read_buf()
1423 return BufferedWriter.write(self, b)
1424
1425
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001426class FileIO(RawIOBase):
1427 _fd = -1
1428 _created = False
1429 _readable = False
1430 _writable = False
1431 _appending = False
1432 _seekable = None
1433 _closefd = True
1434
1435 def __init__(self, file, mode='r', closefd=True, opener=None):
1436 """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
1437 writing, exclusive creation or appending. The file will be created if it
1438 doesn't exist when opened for writing or appending; it will be truncated
1439 when opened for writing. A FileExistsError will be raised if it already
1440 exists when opened for creating. Opening a file for creating implies
1441 writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode
1442 to allow simultaneous reading and writing. A custom opener can be used by
1443 passing a callable as *opener*. The underlying file descriptor for the file
1444 object is then obtained by calling opener with (*name*, *flags*).
1445 *opener* must return an open file descriptor (passing os.open as *opener*
1446 results in functionality similar to passing None).
1447 """
1448 if self._fd >= 0:
1449 # Have to close the existing file first.
1450 try:
1451 if self._closefd:
1452 os.close(self._fd)
1453 finally:
1454 self._fd = -1
1455
1456 if isinstance(file, float):
1457 raise TypeError('integer argument expected, got float')
1458 if isinstance(file, int):
1459 fd = file
1460 if fd < 0:
1461 raise ValueError('negative file descriptor')
1462 else:
1463 fd = -1
1464
1465 if not isinstance(mode, str):
1466 raise TypeError('invalid mode: %s' % (mode,))
1467 if not set(mode) <= set('xrwab+'):
1468 raise ValueError('invalid mode: %s' % (mode,))
1469 if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1:
1470 raise ValueError('Must have exactly one of create/read/write/append '
1471 'mode and at most one plus')
1472
1473 if 'x' in mode:
1474 self._created = True
1475 self._writable = True
1476 flags = os.O_EXCL | os.O_CREAT
1477 elif 'r' in mode:
1478 self._readable = True
1479 flags = 0
1480 elif 'w' in mode:
1481 self._writable = True
1482 flags = os.O_CREAT | os.O_TRUNC
1483 elif 'a' in mode:
1484 self._writable = True
1485 self._appending = True
1486 flags = os.O_APPEND | os.O_CREAT
1487
1488 if '+' in mode:
1489 self._readable = True
1490 self._writable = True
1491
1492 if self._readable and self._writable:
1493 flags |= os.O_RDWR
1494 elif self._readable:
1495 flags |= os.O_RDONLY
1496 else:
1497 flags |= os.O_WRONLY
1498
1499 flags |= getattr(os, 'O_BINARY', 0)
1500
1501 noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or
1502 getattr(os, 'O_CLOEXEC', 0))
1503 flags |= noinherit_flag
1504
1505 owned_fd = None
1506 try:
1507 if fd < 0:
1508 if not closefd:
1509 raise ValueError('Cannot use closefd=False with file name')
1510 if opener is None:
1511 fd = os.open(file, flags, 0o666)
1512 else:
1513 fd = opener(file, flags)
1514 if not isinstance(fd, int):
1515 raise TypeError('expected integer from opener')
1516 if fd < 0:
1517 raise OSError('Negative file descriptor')
1518 owned_fd = fd
1519 if not noinherit_flag:
1520 os.set_inheritable(fd, False)
1521
1522 self._closefd = closefd
1523 fdfstat = os.fstat(fd)
1524 try:
1525 if stat.S_ISDIR(fdfstat.st_mode):
1526 raise IsADirectoryError(errno.EISDIR,
1527 os.strerror(errno.EISDIR), file)
1528 except AttributeError:
1529 # Ignore the AttribueError if stat.S_ISDIR or errno.EISDIR
1530 # don't exist.
1531 pass
1532 self._blksize = getattr(fdfstat, 'st_blksize', 0)
1533 if self._blksize <= 1:
1534 self._blksize = DEFAULT_BUFFER_SIZE
1535
1536 if _setmode:
1537 # don't translate newlines (\r\n <=> \n)
1538 _setmode(fd, os.O_BINARY)
1539
1540 self.name = file
1541 if self._appending:
1542 # For consistent behaviour, we explicitly seek to the
1543 # end of file (otherwise, it might be done only on the
1544 # first write()).
1545 os.lseek(fd, 0, SEEK_END)
1546 except:
1547 if owned_fd is not None:
1548 os.close(owned_fd)
1549 raise
1550 self._fd = fd
1551
1552 def __del__(self):
1553 if self._fd >= 0 and self._closefd and not self.closed:
1554 import warnings
1555 warnings.warn('unclosed file %r' % (self,), ResourceWarning,
Victor Stinnere19558a2016-03-23 00:28:08 +01001556 stacklevel=2, source=self)
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001557 self.close()
1558
1559 def __getstate__(self):
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +02001560 raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001561
1562 def __repr__(self):
1563 class_name = '%s.%s' % (self.__class__.__module__,
1564 self.__class__.__qualname__)
1565 if self.closed:
1566 return '<%s [closed]>' % class_name
1567 try:
1568 name = self.name
1569 except AttributeError:
1570 return ('<%s fd=%d mode=%r closefd=%r>' %
1571 (class_name, self._fd, self.mode, self._closefd))
1572 else:
1573 return ('<%s name=%r mode=%r closefd=%r>' %
1574 (class_name, name, self.mode, self._closefd))
1575
1576 def _checkReadable(self):
1577 if not self._readable:
1578 raise UnsupportedOperation('File not open for reading')
1579
1580 def _checkWritable(self, msg=None):
1581 if not self._writable:
1582 raise UnsupportedOperation('File not open for writing')
1583
1584 def read(self, size=None):
1585 """Read at most size bytes, returned as bytes.
1586
1587 Only makes one system call, so less data may be returned than requested
1588 In non-blocking mode, returns None if no data is available.
1589 Return an empty bytes object at EOF.
1590 """
1591 self._checkClosed()
1592 self._checkReadable()
1593 if size is None or size < 0:
1594 return self.readall()
1595 try:
1596 return os.read(self._fd, size)
1597 except BlockingIOError:
1598 return None
1599
1600 def readall(self):
1601 """Read all data from the file, returned as bytes.
1602
1603 In non-blocking mode, returns as much as is immediately available,
1604 or None if no data is available. Return an empty bytes object at EOF.
1605 """
1606 self._checkClosed()
1607 self._checkReadable()
1608 bufsize = DEFAULT_BUFFER_SIZE
1609 try:
1610 pos = os.lseek(self._fd, 0, SEEK_CUR)
1611 end = os.fstat(self._fd).st_size
1612 if end >= pos:
1613 bufsize = end - pos + 1
1614 except OSError:
1615 pass
1616
1617 result = bytearray()
1618 while True:
1619 if len(result) >= bufsize:
1620 bufsize = len(result)
1621 bufsize += max(bufsize, DEFAULT_BUFFER_SIZE)
1622 n = bufsize - len(result)
1623 try:
1624 chunk = os.read(self._fd, n)
1625 except BlockingIOError:
1626 if result:
1627 break
1628 return None
1629 if not chunk: # reached the end of the file
1630 break
1631 result += chunk
1632
1633 return bytes(result)
1634
1635 def readinto(self, b):
1636 """Same as RawIOBase.readinto()."""
1637 m = memoryview(b).cast('B')
1638 data = self.read(len(m))
1639 n = len(data)
1640 m[:n] = data
1641 return n
1642
1643 def write(self, b):
1644 """Write bytes b to file, return number written.
1645
1646 Only makes one system call, so not all of the data may be written.
1647 The number of bytes actually written is returned. In non-blocking mode,
1648 returns None if the write would block.
1649 """
1650 self._checkClosed()
1651 self._checkWritable()
1652 try:
1653 return os.write(self._fd, b)
1654 except BlockingIOError:
1655 return None
1656
1657 def seek(self, pos, whence=SEEK_SET):
1658 """Move to new file position.
1659
1660 Argument offset is a byte count. Optional argument whence defaults to
1661 SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
1662 are SEEK_CUR or 1 (move relative to current position, positive or negative),
1663 and SEEK_END or 2 (move relative to end of file, usually negative, although
1664 many platforms allow seeking beyond the end of a file).
1665
1666 Note that not all file objects are seekable.
1667 """
1668 if isinstance(pos, float):
1669 raise TypeError('an integer is required')
1670 self._checkClosed()
1671 return os.lseek(self._fd, pos, whence)
1672
1673 def tell(self):
1674 """tell() -> int. Current file position.
1675
1676 Can raise OSError for non seekable files."""
1677 self._checkClosed()
1678 return os.lseek(self._fd, 0, SEEK_CUR)
1679
1680 def truncate(self, size=None):
1681 """Truncate the file to at most size bytes.
1682
1683 Size defaults to the current file position, as returned by tell().
1684 The current file position is changed to the value of size.
1685 """
1686 self._checkClosed()
1687 self._checkWritable()
1688 if size is None:
1689 size = self.tell()
1690 os.ftruncate(self._fd, size)
1691 return size
1692
1693 def close(self):
1694 """Close the file.
1695
1696 A closed file cannot be used for further I/O operations. close() may be
1697 called more than once without error.
1698 """
1699 if not self.closed:
1700 try:
1701 if self._closefd:
1702 os.close(self._fd)
1703 finally:
1704 super().close()
1705
1706 def seekable(self):
1707 """True if file supports random-access."""
1708 self._checkClosed()
1709 if self._seekable is None:
1710 try:
1711 self.tell()
1712 except OSError:
1713 self._seekable = False
1714 else:
1715 self._seekable = True
1716 return self._seekable
1717
1718 def readable(self):
1719 """True if file was opened in a read mode."""
1720 self._checkClosed()
1721 return self._readable
1722
1723 def writable(self):
1724 """True if file was opened in a write mode."""
1725 self._checkClosed()
1726 return self._writable
1727
1728 def fileno(self):
1729 """Return the underlying file descriptor (an integer)."""
1730 self._checkClosed()
1731 return self._fd
1732
1733 def isatty(self):
1734 """True if the file is connected to a TTY device."""
1735 self._checkClosed()
1736 return os.isatty(self._fd)
1737
1738 @property
1739 def closefd(self):
1740 """True if the file descriptor will be closed by close()."""
1741 return self._closefd
1742
1743 @property
1744 def mode(self):
1745 """String giving the file mode"""
1746 if self._created:
1747 if self._readable:
1748 return 'xb+'
1749 else:
1750 return 'xb'
1751 elif self._appending:
1752 if self._readable:
1753 return 'ab+'
1754 else:
1755 return 'ab'
1756 elif self._readable:
1757 if self._writable:
1758 return 'rb+'
1759 else:
1760 return 'rb'
1761 else:
1762 return 'wb'
1763
1764
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001765class TextIOBase(IOBase):
1766
1767 """Base class for text I/O.
1768
1769 This class provides a character and line based interface to stream
Steve Palmer7b97ab32019-04-09 05:35:27 +01001770 I/O. There is no public constructor.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001771 """
1772
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001773 def read(self, size=-1):
1774 """Read at most size characters from stream, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001775
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001776 Read from underlying buffer until we have size characters or we hit EOF.
1777 If size is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001778
1779 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001780 """
1781 self._unsupported("read")
1782
Raymond Hettinger3c940242011-01-12 23:39:31 +00001783 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001784 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001785 self._unsupported("write")
1786
Georg Brandl4d73b572011-01-13 07:13:06 +00001787 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001788 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001789 self._unsupported("truncate")
1790
Raymond Hettinger3c940242011-01-12 23:39:31 +00001791 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001792 """Read until newline or EOF.
1793
1794 Returns an empty string if EOF is hit immediately.
1795 """
1796 self._unsupported("readline")
1797
Raymond Hettinger3c940242011-01-12 23:39:31 +00001798 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001799 """
1800 Separate the underlying buffer from the TextIOBase and return it.
1801
1802 After the underlying buffer has been detached, the TextIO is in an
1803 unusable state.
1804 """
1805 self._unsupported("detach")
1806
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001807 @property
1808 def encoding(self):
1809 """Subclasses should override."""
1810 return None
1811
1812 @property
1813 def newlines(self):
1814 """Line endings translated so far.
1815
1816 Only line endings translated during reading are considered.
1817
1818 Subclasses should override.
1819 """
1820 return None
1821
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001822 @property
1823 def errors(self):
1824 """Error setting of the decoder or encoder.
1825
1826 Subclasses should override."""
1827 return None
1828
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001829io.TextIOBase.register(TextIOBase)
1830
1831
1832class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1833 r"""Codec used when reading a file in universal newlines mode. It wraps
1834 another incremental decoder, translating \r\n and \r into \n. It also
1835 records the types of newlines encountered. When used with
1836 translate=False, it ensures that the newline sequence is returned in
1837 one piece.
1838 """
1839 def __init__(self, decoder, translate, errors='strict'):
1840 codecs.IncrementalDecoder.__init__(self, errors=errors)
1841 self.translate = translate
1842 self.decoder = decoder
1843 self.seennl = 0
1844 self.pendingcr = False
1845
1846 def decode(self, input, final=False):
1847 # decode input (with the eventual \r from a previous pass)
1848 if self.decoder is None:
1849 output = input
1850 else:
1851 output = self.decoder.decode(input, final=final)
1852 if self.pendingcr and (output or final):
1853 output = "\r" + output
1854 self.pendingcr = False
1855
1856 # retain last \r even when not translating data:
1857 # then readline() is sure to get \r\n in one pass
1858 if output.endswith("\r") and not final:
1859 output = output[:-1]
1860 self.pendingcr = True
1861
1862 # Record which newlines are read
1863 crlf = output.count('\r\n')
1864 cr = output.count('\r') - crlf
1865 lf = output.count('\n') - crlf
1866 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1867 | (crlf and self._CRLF)
1868
1869 if self.translate:
1870 if crlf:
1871 output = output.replace("\r\n", "\n")
1872 if cr:
1873 output = output.replace("\r", "\n")
1874
1875 return output
1876
1877 def getstate(self):
1878 if self.decoder is None:
1879 buf = b""
1880 flag = 0
1881 else:
1882 buf, flag = self.decoder.getstate()
1883 flag <<= 1
1884 if self.pendingcr:
1885 flag |= 1
1886 return buf, flag
1887
1888 def setstate(self, state):
1889 buf, flag = state
1890 self.pendingcr = bool(flag & 1)
1891 if self.decoder is not None:
1892 self.decoder.setstate((buf, flag >> 1))
1893
1894 def reset(self):
1895 self.seennl = 0
1896 self.pendingcr = False
1897 if self.decoder is not None:
1898 self.decoder.reset()
1899
1900 _LF = 1
1901 _CR = 2
1902 _CRLF = 4
1903
1904 @property
1905 def newlines(self):
1906 return (None,
1907 "\n",
1908 "\r",
1909 ("\r", "\n"),
1910 "\r\n",
1911 ("\n", "\r\n"),
1912 ("\r", "\r\n"),
1913 ("\r", "\n", "\r\n")
1914 )[self.seennl]
1915
1916
1917class TextIOWrapper(TextIOBase):
1918
1919 r"""Character and line based layer over a BufferedIOBase object, buffer.
1920
1921 encoding gives the name of the encoding that the stream will be
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001922 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001923
1924 errors determines the strictness of encoding and decoding (see the
1925 codecs.register) and defaults to "strict".
1926
1927 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1928 handling of line endings. If it is None, universal newlines is
1929 enabled. With this enabled, on input, the lines endings '\n', '\r',
1930 or '\r\n' are translated to '\n' before being returned to the
1931 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001932 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001933 legal values, that newline becomes the newline when the file is read
1934 and it is returned untranslated. On output, '\n' is converted to the
1935 newline.
1936
1937 If line_buffering is True, a call to flush is implied when a call to
1938 write contains a newline character.
1939 """
1940
1941 _CHUNK_SIZE = 2048
1942
Andrew Svetlov4e9e9c12012-08-13 16:09:54 +03001943 # The write_through argument has no effect here since this
1944 # implementation always writes through. The argument is present only
1945 # so that the signature can match the signature of the C version.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001946 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001947 line_buffering=False, write_through=False):
INADA Naoki507434f2017-12-21 09:59:53 +09001948 self._check_newline(newline)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001949 if encoding is None:
1950 try:
1951 encoding = os.device_encoding(buffer.fileno())
1952 except (AttributeError, UnsupportedOperation):
1953 pass
1954 if encoding is None:
1955 try:
1956 import locale
Brett Cannoncd171c82013-07-04 17:43:24 -04001957 except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001958 # Importing locale may fail if Python is being built
1959 encoding = "ascii"
1960 else:
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001961 encoding = locale.getpreferredencoding(False)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001962
1963 if not isinstance(encoding, str):
1964 raise ValueError("invalid encoding: %r" % encoding)
1965
Nick Coghlana9b15242014-02-04 22:11:18 +10001966 if not codecs.lookup(encoding)._is_text_encoding:
1967 msg = ("%r is not a text encoding; "
1968 "use codecs.open() to handle arbitrary codecs")
1969 raise LookupError(msg % encoding)
1970
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001971 if errors is None:
1972 errors = "strict"
1973 else:
1974 if not isinstance(errors, str):
1975 raise ValueError("invalid errors: %r" % errors)
1976
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001977 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001978 self._decoded_chars = '' # buffer for text returned from decoder
1979 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1980 self._snapshot = None # info for reconstructing decoder state
1981 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001982 self._has_read1 = hasattr(self.buffer, 'read1')
INADA Naoki507434f2017-12-21 09:59:53 +09001983 self._configure(encoding, errors, newline,
1984 line_buffering, write_through)
1985
1986 def _check_newline(self, newline):
1987 if newline is not None and not isinstance(newline, str):
1988 raise TypeError("illegal newline type: %r" % (type(newline),))
1989 if newline not in (None, "", "\n", "\r", "\r\n"):
1990 raise ValueError("illegal newline value: %r" % (newline,))
1991
1992 def _configure(self, encoding=None, errors=None, newline=None,
1993 line_buffering=False, write_through=False):
1994 self._encoding = encoding
1995 self._errors = errors
1996 self._encoder = None
1997 self._decoder = None
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001998 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001999
INADA Naoki507434f2017-12-21 09:59:53 +09002000 self._readuniversal = not newline
2001 self._readtranslate = newline is None
2002 self._readnl = newline
2003 self._writetranslate = newline != ''
2004 self._writenl = newline or os.linesep
2005
2006 self._line_buffering = line_buffering
2007 self._write_through = write_through
2008
2009 # don't write a BOM in the middle of a file
Antoine Pitroue4501852009-05-14 18:55:55 +00002010 if self._seekable and self.writable():
2011 position = self.buffer.tell()
2012 if position != 0:
2013 try:
2014 self._get_encoder().setstate(0)
2015 except LookupError:
2016 # Sometimes the encoder doesn't exist
2017 pass
2018
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002019 # self._snapshot is either None, or a tuple (dec_flags, next_input)
2020 # where dec_flags is the second (integer) item of the decoder state
2021 # and next_input is the chunk of input bytes that comes next after the
2022 # snapshot point. We use this to reconstruct decoder states in tell().
2023
2024 # Naming convention:
2025 # - "bytes_..." for integer variables that count input bytes
2026 # - "chars_..." for integer variables that count decoded characters
2027
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00002028 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +03002029 result = "<{}.{}".format(self.__class__.__module__,
2030 self.__class__.__qualname__)
Antoine Pitrou716c4442009-05-23 19:04:03 +00002031 try:
2032 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -06002033 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002034 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00002035 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002036 result += " name={0!r}".format(name)
2037 try:
2038 mode = self.mode
Benjamin Peterson10e76b62014-12-21 20:51:50 -06002039 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002040 pass
2041 else:
2042 result += " mode={0!r}".format(mode)
2043 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00002044
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002045 @property
2046 def encoding(self):
2047 return self._encoding
2048
2049 @property
2050 def errors(self):
2051 return self._errors
2052
2053 @property
2054 def line_buffering(self):
2055 return self._line_buffering
2056
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002057 @property
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002058 def write_through(self):
2059 return self._write_through
2060
2061 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002062 def buffer(self):
2063 return self._buffer
2064
INADA Naoki507434f2017-12-21 09:59:53 +09002065 def reconfigure(self, *,
2066 encoding=None, errors=None, newline=Ellipsis,
2067 line_buffering=None, write_through=None):
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002068 """Reconfigure the text stream with new parameters.
2069
2070 This also flushes the stream.
2071 """
INADA Naoki507434f2017-12-21 09:59:53 +09002072 if (self._decoder is not None
2073 and (encoding is not None or errors is not None
2074 or newline is not Ellipsis)):
2075 raise UnsupportedOperation(
2076 "It is not possible to set the encoding or newline of stream "
2077 "after the first read")
2078
2079 if errors is None:
2080 if encoding is None:
2081 errors = self._errors
2082 else:
2083 errors = 'strict'
2084 elif not isinstance(errors, str):
2085 raise TypeError("invalid errors: %r" % errors)
2086
2087 if encoding is None:
2088 encoding = self._encoding
2089 else:
2090 if not isinstance(encoding, str):
2091 raise TypeError("invalid encoding: %r" % encoding)
2092
2093 if newline is Ellipsis:
2094 newline = self._readnl
2095 self._check_newline(newline)
2096
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002097 if line_buffering is None:
2098 line_buffering = self.line_buffering
2099 if write_through is None:
2100 write_through = self.write_through
INADA Naoki507434f2017-12-21 09:59:53 +09002101
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002102 self.flush()
INADA Naoki507434f2017-12-21 09:59:53 +09002103 self._configure(encoding, errors, newline,
2104 line_buffering, write_through)
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002105
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002106 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02002107 if self.closed:
2108 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002109 return self._seekable
2110
2111 def readable(self):
2112 return self.buffer.readable()
2113
2114 def writable(self):
2115 return self.buffer.writable()
2116
2117 def flush(self):
2118 self.buffer.flush()
2119 self._telling = self._seekable
2120
2121 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00002122 if self.buffer is not None and not self.closed:
Benjamin Peterson68623612012-12-20 11:53:11 -06002123 try:
2124 self.flush()
2125 finally:
2126 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002127
2128 @property
2129 def closed(self):
2130 return self.buffer.closed
2131
2132 @property
2133 def name(self):
2134 return self.buffer.name
2135
2136 def fileno(self):
2137 return self.buffer.fileno()
2138
2139 def isatty(self):
2140 return self.buffer.isatty()
2141
Raymond Hettinger00fa0392011-01-13 02:52:26 +00002142 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00002143 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002144 if self.closed:
2145 raise ValueError("write to closed file")
2146 if not isinstance(s, str):
2147 raise TypeError("can't write %s to text stream" %
2148 s.__class__.__name__)
2149 length = len(s)
2150 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
2151 if haslf and self._writetranslate and self._writenl != "\n":
2152 s = s.replace("\n", self._writenl)
2153 encoder = self._encoder or self._get_encoder()
2154 # XXX What if we were just reading?
2155 b = encoder.encode(s)
2156 self.buffer.write(b)
2157 if self._line_buffering and (haslf or "\r" in s):
2158 self.flush()
Zackery Spytz23db9352018-06-29 04:14:58 -06002159 self._set_decoded_chars('')
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002160 self._snapshot = None
2161 if self._decoder:
2162 self._decoder.reset()
2163 return length
2164
2165 def _get_encoder(self):
2166 make_encoder = codecs.getincrementalencoder(self._encoding)
2167 self._encoder = make_encoder(self._errors)
2168 return self._encoder
2169
2170 def _get_decoder(self):
2171 make_decoder = codecs.getincrementaldecoder(self._encoding)
2172 decoder = make_decoder(self._errors)
2173 if self._readuniversal:
2174 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
2175 self._decoder = decoder
2176 return decoder
2177
2178 # The following three methods implement an ADT for _decoded_chars.
2179 # Text returned from the decoder is buffered here until the client
2180 # requests it by calling our read() or readline() method.
2181 def _set_decoded_chars(self, chars):
2182 """Set the _decoded_chars buffer."""
2183 self._decoded_chars = chars
2184 self._decoded_chars_used = 0
2185
2186 def _get_decoded_chars(self, n=None):
2187 """Advance into the _decoded_chars buffer."""
2188 offset = self._decoded_chars_used
2189 if n is None:
2190 chars = self._decoded_chars[offset:]
2191 else:
2192 chars = self._decoded_chars[offset:offset + n]
2193 self._decoded_chars_used += len(chars)
2194 return chars
2195
2196 def _rewind_decoded_chars(self, n):
2197 """Rewind the _decoded_chars buffer."""
2198 if self._decoded_chars_used < n:
2199 raise AssertionError("rewind decoded_chars out of bounds")
2200 self._decoded_chars_used -= n
2201
2202 def _read_chunk(self):
2203 """
2204 Read and decode the next chunk of data from the BufferedReader.
2205 """
2206
2207 # The return value is True unless EOF was reached. The decoded
2208 # string is placed in self._decoded_chars (replacing its previous
2209 # value). The entire input chunk is sent to the decoder, though
2210 # some of it may remain buffered in the decoder, yet to be
2211 # converted.
2212
2213 if self._decoder is None:
2214 raise ValueError("no decoder")
2215
2216 if self._telling:
2217 # To prepare for tell(), we need to snapshot a point in the
2218 # file where the decoder's input buffer is empty.
2219
2220 dec_buffer, dec_flags = self._decoder.getstate()
2221 # Given this, we know there was a valid snapshot point
2222 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
2223
2224 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02002225 if self._has_read1:
2226 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
2227 else:
2228 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002229 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002230 decoded_chars = self._decoder.decode(input_chunk, eof)
2231 self._set_decoded_chars(decoded_chars)
2232 if decoded_chars:
2233 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
2234 else:
2235 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002236
2237 if self._telling:
2238 # At the snapshot point, len(dec_buffer) bytes before the read,
2239 # the next input to be decoded is dec_buffer + input_chunk.
2240 self._snapshot = (dec_flags, dec_buffer + input_chunk)
2241
2242 return not eof
2243
2244 def _pack_cookie(self, position, dec_flags=0,
2245 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
2246 # The meaning of a tell() cookie is: seek to position, set the
2247 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
2248 # into the decoder with need_eof as the EOF flag, then skip
2249 # chars_to_skip characters of the decoded result. For most simple
2250 # decoders, tell() will often just give a byte offset in the file.
2251 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
2252 (chars_to_skip<<192) | bool(need_eof)<<256)
2253
2254 def _unpack_cookie(self, bigint):
2255 rest, position = divmod(bigint, 1<<64)
2256 rest, dec_flags = divmod(rest, 1<<64)
2257 rest, bytes_to_feed = divmod(rest, 1<<64)
2258 need_eof, chars_to_skip = divmod(rest, 1<<64)
2259 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
2260
2261 def tell(self):
2262 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002263 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002264 if not self._telling:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002265 raise OSError("telling position disabled by next() call")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002266 self.flush()
2267 position = self.buffer.tell()
2268 decoder = self._decoder
2269 if decoder is None or self._snapshot is None:
2270 if self._decoded_chars:
2271 # This should never happen.
2272 raise AssertionError("pending decoded text")
2273 return position
2274
2275 # Skip backward to the snapshot point (see _read_chunk).
2276 dec_flags, next_input = self._snapshot
2277 position -= len(next_input)
2278
2279 # How many decoded characters have been used up since the snapshot?
2280 chars_to_skip = self._decoded_chars_used
2281 if chars_to_skip == 0:
2282 # We haven't moved from the snapshot point.
2283 return self._pack_cookie(position, dec_flags)
2284
2285 # Starting from the snapshot position, we will walk the decoder
2286 # forward until it gives us enough decoded characters.
2287 saved_state = decoder.getstate()
2288 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002289 # Fast search for an acceptable start point, close to our
2290 # current pos.
2291 # Rationale: calling decoder.decode() has a large overhead
2292 # regardless of chunk size; we want the number of such calls to
Raymond Hettinger14010182018-09-13 21:17:40 -07002293 # be O(1) in most situations (common decoders, sensible input).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002294 # Actually, it will be exactly 1 for fixed-size codecs (all
2295 # 8-bit codecs, also UTF-16 and UTF-32).
2296 skip_bytes = int(self._b2cratio * chars_to_skip)
2297 skip_back = 1
2298 assert skip_bytes <= len(next_input)
2299 while skip_bytes > 0:
2300 decoder.setstate((b'', dec_flags))
2301 # Decode up to temptative start point
2302 n = len(decoder.decode(next_input[:skip_bytes]))
2303 if n <= chars_to_skip:
2304 b, d = decoder.getstate()
2305 if not b:
2306 # Before pos and no bytes buffered in decoder => OK
2307 dec_flags = d
2308 chars_to_skip -= n
2309 break
2310 # Skip back by buffered amount and reset heuristic
2311 skip_bytes -= len(b)
2312 skip_back = 1
2313 else:
2314 # We're too far ahead, skip back a bit
2315 skip_bytes -= skip_back
2316 skip_back = skip_back * 2
2317 else:
2318 skip_bytes = 0
2319 decoder.setstate((b'', dec_flags))
2320
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002321 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002322 start_pos = position + skip_bytes
2323 start_flags = dec_flags
2324 if chars_to_skip == 0:
2325 # We haven't moved from the start point.
2326 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002327
2328 # Feed the decoder one byte at a time. As we go, note the
2329 # nearest "safe start point" before the current location
2330 # (a point where the decoder has nothing buffered, so seek()
2331 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002332 bytes_fed = 0
2333 need_eof = 0
2334 # Chars decoded since `start_pos`
2335 chars_decoded = 0
2336 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002337 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002338 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002339 dec_buffer, dec_flags = decoder.getstate()
2340 if not dec_buffer and chars_decoded <= chars_to_skip:
2341 # Decoder buffer is empty, so this is a safe start point.
2342 start_pos += bytes_fed
2343 chars_to_skip -= chars_decoded
2344 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
2345 if chars_decoded >= chars_to_skip:
2346 break
2347 else:
2348 # We didn't get enough decoded data; signal EOF to get more.
2349 chars_decoded += len(decoder.decode(b'', final=True))
2350 need_eof = 1
2351 if chars_decoded < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002352 raise OSError("can't reconstruct logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002353
2354 # The returned cookie corresponds to the last safe start point.
2355 return self._pack_cookie(
2356 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
2357 finally:
2358 decoder.setstate(saved_state)
2359
2360 def truncate(self, pos=None):
2361 self.flush()
2362 if pos is None:
2363 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00002364 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002365
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002366 def detach(self):
2367 if self.buffer is None:
2368 raise ValueError("buffer is already detached")
2369 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002370 buffer = self._buffer
2371 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002372 return buffer
2373
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002374 def seek(self, cookie, whence=0):
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002375 def _reset_encoder(position):
2376 """Reset the encoder (merely useful for proper BOM handling)"""
2377 try:
2378 encoder = self._encoder or self._get_encoder()
2379 except LookupError:
2380 # Sometimes the encoder doesn't exist
2381 pass
2382 else:
2383 if position != 0:
2384 encoder.setstate(0)
2385 else:
2386 encoder.reset()
2387
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002388 if self.closed:
2389 raise ValueError("tell on closed file")
2390 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002391 raise UnsupportedOperation("underlying stream is not seekable")
ngie-eign848037c2019-03-02 23:28:26 -08002392 if whence == SEEK_CUR:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002393 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002394 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002395 # Seeking to the current position should attempt to
2396 # sync the underlying buffer with the current position.
2397 whence = 0
2398 cookie = self.tell()
ngie-eign848037c2019-03-02 23:28:26 -08002399 elif whence == SEEK_END:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002400 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002401 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002402 self.flush()
ngie-eign848037c2019-03-02 23:28:26 -08002403 position = self.buffer.seek(0, whence)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002404 self._set_decoded_chars('')
2405 self._snapshot = None
2406 if self._decoder:
2407 self._decoder.reset()
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002408 _reset_encoder(position)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002409 return position
2410 if whence != 0:
Jesus Cea94363612012-06-22 18:32:07 +02002411 raise ValueError("unsupported whence (%r)" % (whence,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002412 if cookie < 0:
2413 raise ValueError("negative seek position %r" % (cookie,))
2414 self.flush()
2415
2416 # The strategy of seek() is to go back to the safe start point
2417 # and replay the effect of read(chars_to_skip) from there.
2418 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
2419 self._unpack_cookie(cookie)
2420
2421 # Seek back to the safe start point.
2422 self.buffer.seek(start_pos)
2423 self._set_decoded_chars('')
2424 self._snapshot = None
2425
2426 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00002427 if cookie == 0 and self._decoder:
2428 self._decoder.reset()
2429 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002430 self._decoder = self._decoder or self._get_decoder()
2431 self._decoder.setstate((b'', dec_flags))
2432 self._snapshot = (dec_flags, b'')
2433
2434 if chars_to_skip:
2435 # Just like _read_chunk, feed the decoder and save a snapshot.
2436 input_chunk = self.buffer.read(bytes_to_feed)
2437 self._set_decoded_chars(
2438 self._decoder.decode(input_chunk, need_eof))
2439 self._snapshot = (dec_flags, input_chunk)
2440
2441 # Skip chars_to_skip of the decoded characters.
2442 if len(self._decoded_chars) < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002443 raise OSError("can't restore logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002444 self._decoded_chars_used = chars_to_skip
2445
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002446 _reset_encoder(cookie)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002447 return cookie
2448
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002449 def read(self, size=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00002450 self._checkReadable()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002451 if size is None:
2452 size = -1
Oren Milmande503602017-08-24 21:33:42 +03002453 else:
2454 try:
2455 size_index = size.__index__
2456 except AttributeError:
2457 raise TypeError(f"{size!r} is not an integer")
2458 else:
2459 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002460 decoder = self._decoder or self._get_decoder()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002461 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002462 # Read everything.
2463 result = (self._get_decoded_chars() +
2464 decoder.decode(self.buffer.read(), final=True))
2465 self._set_decoded_chars('')
2466 self._snapshot = None
2467 return result
2468 else:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002469 # Keep reading chunks until we have size characters to return.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002470 eof = False
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002471 result = self._get_decoded_chars(size)
2472 while len(result) < size and not eof:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002473 eof = not self._read_chunk()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002474 result += self._get_decoded_chars(size - len(result))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002475 return result
2476
2477 def __next__(self):
2478 self._telling = False
2479 line = self.readline()
2480 if not line:
2481 self._snapshot = None
2482 self._telling = self._seekable
2483 raise StopIteration
2484 return line
2485
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002486 def readline(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002487 if self.closed:
2488 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002489 if size is None:
2490 size = -1
Oren Milmande503602017-08-24 21:33:42 +03002491 else:
2492 try:
2493 size_index = size.__index__
2494 except AttributeError:
2495 raise TypeError(f"{size!r} is not an integer")
2496 else:
2497 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002498
2499 # Grab all the decoded text (we will rewind any extra bits later).
2500 line = self._get_decoded_chars()
2501
2502 start = 0
2503 # Make the decoder if it doesn't already exist.
2504 if not self._decoder:
2505 self._get_decoder()
2506
2507 pos = endpos = None
2508 while True:
2509 if self._readtranslate:
2510 # Newlines are already translated, only search for \n
2511 pos = line.find('\n', start)
2512 if pos >= 0:
2513 endpos = pos + 1
2514 break
2515 else:
2516 start = len(line)
2517
2518 elif self._readuniversal:
2519 # Universal newline search. Find any of \r, \r\n, \n
2520 # The decoder ensures that \r\n are not split in two pieces
2521
2522 # In C we'd look for these in parallel of course.
2523 nlpos = line.find("\n", start)
2524 crpos = line.find("\r", start)
2525 if crpos == -1:
2526 if nlpos == -1:
2527 # Nothing found
2528 start = len(line)
2529 else:
2530 # Found \n
2531 endpos = nlpos + 1
2532 break
2533 elif nlpos == -1:
2534 # Found lone \r
2535 endpos = crpos + 1
2536 break
2537 elif nlpos < crpos:
2538 # Found \n
2539 endpos = nlpos + 1
2540 break
2541 elif nlpos == crpos + 1:
2542 # Found \r\n
2543 endpos = crpos + 2
2544 break
2545 else:
2546 # Found \r
2547 endpos = crpos + 1
2548 break
2549 else:
2550 # non-universal
2551 pos = line.find(self._readnl)
2552 if pos >= 0:
2553 endpos = pos + len(self._readnl)
2554 break
2555
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002556 if size >= 0 and len(line) >= size:
2557 endpos = size # reached length size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002558 break
2559
2560 # No line ending seen yet - get more data'
2561 while self._read_chunk():
2562 if self._decoded_chars:
2563 break
2564 if self._decoded_chars:
2565 line += self._get_decoded_chars()
2566 else:
2567 # end of file
2568 self._set_decoded_chars('')
2569 self._snapshot = None
2570 return line
2571
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002572 if size >= 0 and endpos > size:
2573 endpos = size # don't exceed size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002574
2575 # Rewind _decoded_chars to just after the line ending we found.
2576 self._rewind_decoded_chars(len(line) - endpos)
2577 return line[:endpos]
2578
2579 @property
2580 def newlines(self):
2581 return self._decoder.newlines if self._decoder else None
2582
2583
2584class StringIO(TextIOWrapper):
2585 """Text I/O implementation using an in-memory buffer.
2586
2587 The initial_value argument sets the value of object. The newline
2588 argument is like the one of TextIOWrapper's constructor.
2589 """
2590
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002591 def __init__(self, initial_value="", newline="\n"):
2592 super(StringIO, self).__init__(BytesIO(),
2593 encoding="utf-8",
Serhiy Storchakac92ea762014-01-29 11:33:26 +02002594 errors="surrogatepass",
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002595 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002596 # Issue #5645: make universal newlines semantics the same as in the
2597 # C version, even under Windows.
2598 if newline is None:
2599 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002600 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002601 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002602 raise TypeError("initial_value must be str or None, not {0}"
2603 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002604 self.write(initial_value)
2605 self.seek(0)
2606
2607 def getvalue(self):
2608 self.flush()
Antoine Pitrou57839a62014-02-02 23:37:29 +01002609 decoder = self._decoder or self._get_decoder()
2610 old_state = decoder.getstate()
2611 decoder.reset()
2612 try:
2613 return decoder.decode(self.buffer.getvalue(), final=True)
2614 finally:
2615 decoder.setstate(old_state)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002616
2617 def __repr__(self):
2618 # TextIOWrapper tells the encoding in its repr. In StringIO,
Martin Panter7462b6492015-11-02 03:37:02 +00002619 # that's an implementation detail.
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002620 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002621
2622 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002623 def errors(self):
2624 return None
2625
2626 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002627 def encoding(self):
2628 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002629
2630 def detach(self):
2631 # This doesn't make sense on StringIO.
2632 self._unsupported("detach")