blob: 6833883dadbdd9e61cdcd922cbea4ec7134818b0 [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")
201 raw = FileIO(file,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100202 (creating and "x" or "") +
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000203 (reading and "r" or "") +
204 (writing and "w" or "") +
205 (appending and "a" or "") +
206 (updating and "+" or ""),
Ross Lagerwall59142db2011-10-31 20:34:46 +0200207 closefd, opener=opener)
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300208 result = raw
209 try:
210 line_buffering = False
211 if buffering == 1 or buffering < 0 and raw.isatty():
212 buffering = -1
213 line_buffering = True
214 if buffering < 0:
215 buffering = DEFAULT_BUFFER_SIZE
216 try:
217 bs = os.fstat(raw.fileno()).st_blksize
218 except (OSError, AttributeError):
219 pass
220 else:
221 if bs > 1:
222 buffering = bs
223 if buffering < 0:
224 raise ValueError("invalid buffering size")
225 if buffering == 0:
226 if binary:
227 return result
228 raise ValueError("can't have unbuffered text I/O")
229 if updating:
230 buffer = BufferedRandom(raw, buffering)
231 elif creating or writing or appending:
232 buffer = BufferedWriter(raw, buffering)
233 elif reading:
234 buffer = BufferedReader(raw, buffering)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000235 else:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300236 raise ValueError("unknown mode: %r" % mode)
237 result = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000238 if binary:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300239 return result
240 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
241 result = text
242 text.mode = mode
243 return result
244 except:
245 result.close()
246 raise
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000247
248
249class DocDescriptor:
250 """Helper for builtins.open.__doc__
251 """
252 def __get__(self, obj, typ):
253 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000254 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000255 "errors=None, newline=None, closefd=True)\n\n" +
256 open.__doc__)
257
258class OpenWrapper:
259 """Wrapper for builtins.open
260
261 Trick so that open won't become a bound method when stored
262 as a class variable (as dbm.dumb does).
263
Nick Coghland6009512014-11-20 21:39:37 +1000264 See initstdio() in Python/pylifecycle.c.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000265 """
266 __doc__ = DocDescriptor()
267
268 def __new__(cls, *args, **kwargs):
269 return open(*args, **kwargs)
270
271
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000272# In normal operation, both `UnsupportedOperation`s should be bound to the
273# same object.
274try:
275 UnsupportedOperation = io.UnsupportedOperation
276except AttributeError:
Serhiy Storchaka606ab862016-12-07 13:31:20 +0200277 class UnsupportedOperation(OSError, ValueError):
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000278 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000279
280
281class IOBase(metaclass=abc.ABCMeta):
282
283 """The abstract base class for all I/O classes, acting on streams of
284 bytes. There is no public constructor.
285
286 This class provides dummy implementations for many methods that
287 derived classes can override selectively; the default implementations
288 represent a file that cannot be read, written or seeked.
289
290 Even though IOBase does not declare read, readinto, or write because
291 their signatures will vary, implementations and clients should
292 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000293 may raise UnsupportedOperation when operations they do not support are
294 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000295
296 The basic type used for binary data read from or written to a file is
Martin Panter6bb91f32016-05-28 00:41:57 +0000297 bytes. Other bytes-like objects are accepted as method arguments too. In
298 some cases (such as readinto), a writable object is required. Text I/O
299 classes work with str data.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000300
301 Note that calling any method (even inquiries) on a closed stream is
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200302 undefined. Implementations may raise OSError in this case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000303
304 IOBase (and its subclasses) support the iterator protocol, meaning
305 that an IOBase object can be iterated over yielding the lines in a
306 stream.
307
308 IOBase also supports the :keyword:`with` statement. In this example,
309 fp is closed after the suite of the with statement is complete:
310
311 with open('spam.txt', 'r') as fp:
312 fp.write('Spam and eggs!')
313 """
314
315 ### Internal ###
316
Raymond Hettinger3c940242011-01-12 23:39:31 +0000317 def _unsupported(self, name):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200318 """Internal: raise an OSError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000319 raise UnsupportedOperation("%s.%s() not supported" %
320 (self.__class__.__name__, name))
321
322 ### Positioning ###
323
Georg Brandl4d73b572011-01-13 07:13:06 +0000324 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000325 """Change stream position.
326
Terry Jan Reedyc30b7b12013-03-11 17:57:08 -0400327 Change the stream position to byte offset pos. Argument pos is
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000328 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000329 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000330
331 * 0 -- start of stream (the default); offset should be zero or positive
332 * 1 -- current stream position; offset may be negative
333 * 2 -- end of stream; offset is usually negative
Jesus Cea94363612012-06-22 18:32:07 +0200334 Some operating systems / file systems could provide additional values.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000335
Raymond Hettingercbb80892011-01-13 18:15:51 +0000336 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000337 """
338 self._unsupported("seek")
339
Raymond Hettinger3c940242011-01-12 23:39:31 +0000340 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000341 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000342 return self.seek(0, 1)
343
Georg Brandl4d73b572011-01-13 07:13:06 +0000344 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000345 """Truncate file to size bytes.
346
347 Size defaults to the current IO position as reported by tell(). Return
348 the new size.
349 """
350 self._unsupported("truncate")
351
352 ### Flush and close ###
353
Raymond Hettinger3c940242011-01-12 23:39:31 +0000354 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000355 """Flush write buffers, if applicable.
356
357 This is not implemented for read-only and non-blocking streams.
358 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000359 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000360 # XXX Should this return the number of bytes written???
361
362 __closed = False
363
Raymond Hettinger3c940242011-01-12 23:39:31 +0000364 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000365 """Flush and close the IO object.
366
367 This method has no effect if the file is already closed.
368 """
369 if not self.__closed:
Benjamin Peterson68623612012-12-20 11:53:11 -0600370 try:
371 self.flush()
372 finally:
373 self.__closed = True
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000374
Raymond Hettinger3c940242011-01-12 23:39:31 +0000375 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000376 """Destructor. Calls close()."""
377 # The try/except block is in case this is called at program
378 # exit time, when it's possible that globals have already been
379 # deleted, and then the close() call might fail. Since
380 # there's nothing we can do about such failures and they annoy
381 # the end users, we suppress the traceback.
382 try:
383 self.close()
384 except:
385 pass
386
387 ### Inquiries ###
388
Raymond Hettinger3c940242011-01-12 23:39:31 +0000389 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000390 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000391
Martin Panter754aab22016-03-31 07:21:56 +0000392 If False, seek(), tell() and truncate() will raise OSError.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000393 This method may need to do a test seek().
394 """
395 return False
396
397 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000398 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000399 """
400 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000401 raise UnsupportedOperation("File or stream is not seekable."
402 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000403
Raymond Hettinger3c940242011-01-12 23:39:31 +0000404 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000405 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000406
Martin Panter754aab22016-03-31 07:21:56 +0000407 If False, read() will raise OSError.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000408 """
409 return False
410
411 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000412 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000413 """
414 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000415 raise UnsupportedOperation("File or stream is not readable."
416 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000417
Raymond Hettinger3c940242011-01-12 23:39:31 +0000418 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000419 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000420
Martin Panter754aab22016-03-31 07:21:56 +0000421 If False, write() and truncate() will raise OSError.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000422 """
423 return False
424
425 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000426 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000427 """
428 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000429 raise UnsupportedOperation("File or stream is not writable."
430 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000431
432 @property
433 def closed(self):
434 """closed: bool. True iff the file has been closed.
435
436 For backwards compatibility, this is a property, not a predicate.
437 """
438 return self.__closed
439
440 def _checkClosed(self, msg=None):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300441 """Internal: raise a ValueError if file is closed
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000442 """
443 if self.closed:
444 raise ValueError("I/O operation on closed file."
445 if msg is None else msg)
446
447 ### Context manager ###
448
Raymond Hettinger3c940242011-01-12 23:39:31 +0000449 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000450 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000451 self._checkClosed()
452 return self
453
Raymond Hettinger3c940242011-01-12 23:39:31 +0000454 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000455 """Context management protocol. Calls close()"""
456 self.close()
457
458 ### Lower-level APIs ###
459
460 # XXX Should these be present even if unimplemented?
461
Raymond Hettinger3c940242011-01-12 23:39:31 +0000462 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000463 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000464
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200465 An OSError is raised if the IO object does not use a file descriptor.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000466 """
467 self._unsupported("fileno")
468
Raymond Hettinger3c940242011-01-12 23:39:31 +0000469 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000470 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000471
472 Return False if it can't be determined.
473 """
474 self._checkClosed()
475 return False
476
477 ### Readline[s] and writelines ###
478
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300479 def readline(self, size=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000480 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000481
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300482 If size is specified, at most size bytes will be read.
483 Size should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000484
485 The line terminator is always b'\n' for binary files; for text
486 files, the newlines argument to open can be used to select the line
487 terminator(s) recognized.
488 """
489 # For backwards compatibility, a (slowish) readline().
490 if hasattr(self, "peek"):
491 def nreadahead():
492 readahead = self.peek(1)
493 if not readahead:
494 return 1
495 n = (readahead.find(b"\n") + 1) or len(readahead)
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300496 if size >= 0:
497 n = min(n, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000498 return n
499 else:
500 def nreadahead():
501 return 1
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300502 if size is None:
503 size = -1
Oren Milmande503602017-08-24 21:33:42 +0300504 else:
505 try:
506 size_index = size.__index__
507 except AttributeError:
508 raise TypeError(f"{size!r} is not an integer")
509 else:
510 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000511 res = bytearray()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300512 while size < 0 or len(res) < size:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000513 b = self.read(nreadahead())
514 if not b:
515 break
516 res += b
517 if res.endswith(b"\n"):
518 break
519 return bytes(res)
520
521 def __iter__(self):
522 self._checkClosed()
523 return self
524
525 def __next__(self):
526 line = self.readline()
527 if not line:
528 raise StopIteration
529 return line
530
531 def readlines(self, hint=None):
532 """Return a list of lines from the stream.
533
534 hint can be specified to control the number of lines read: no more
535 lines will be read if the total size (in bytes/characters) of all
536 lines so far exceeds hint.
537 """
538 if hint is None or hint <= 0:
539 return list(self)
540 n = 0
541 lines = []
542 for line in self:
543 lines.append(line)
544 n += len(line)
545 if n >= hint:
546 break
547 return lines
548
549 def writelines(self, lines):
550 self._checkClosed()
551 for line in lines:
552 self.write(line)
553
554io.IOBase.register(IOBase)
555
556
557class RawIOBase(IOBase):
558
559 """Base class for raw binary I/O."""
560
561 # The read() method is implemented by calling readinto(); derived
562 # classes that want to support read() only need to implement
563 # readinto() as a primitive operation. In general, readinto() can be
564 # more efficient than read().
565
566 # (It would be tempting to also provide an implementation of
567 # readinto() in terms of read(), in case the latter is a more suitable
568 # primitive operation, but that would lead to nasty recursion in case
569 # a subclass doesn't implement either.)
570
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300571 def read(self, size=-1):
572 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000573
574 Returns an empty bytes object on EOF, or None if the object is
575 set not to block and has no data to read.
576 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300577 if size is None:
578 size = -1
579 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000580 return self.readall()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300581 b = bytearray(size.__index__())
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000582 n = self.readinto(b)
Antoine Pitrou328ec742010-09-14 18:37:24 +0000583 if n is None:
584 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000585 del b[n:]
586 return bytes(b)
587
588 def readall(self):
589 """Read until EOF, using multiple read() call."""
590 res = bytearray()
591 while True:
592 data = self.read(DEFAULT_BUFFER_SIZE)
593 if not data:
594 break
595 res += data
Victor Stinnera80987f2011-05-25 22:47:16 +0200596 if res:
597 return bytes(res)
598 else:
599 # b'' or None
600 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000601
Raymond Hettinger3c940242011-01-12 23:39:31 +0000602 def readinto(self, b):
Martin Panter6bb91f32016-05-28 00:41:57 +0000603 """Read bytes into a pre-allocated bytes-like object b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000604
Raymond Hettingercbb80892011-01-13 18:15:51 +0000605 Returns an int representing the number of bytes read (0 for EOF), or
606 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000607 """
608 self._unsupported("readinto")
609
Raymond Hettinger3c940242011-01-12 23:39:31 +0000610 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000611 """Write the given buffer to the IO stream.
612
Martin Panter6bb91f32016-05-28 00:41:57 +0000613 Returns the number of bytes written, which may be less than the
614 length of b in bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000615 """
616 self._unsupported("write")
617
618io.RawIOBase.register(RawIOBase)
619from _io import FileIO
620RawIOBase.register(FileIO)
621
622
623class BufferedIOBase(IOBase):
624
625 """Base class for buffered IO objects.
626
627 The main difference with RawIOBase is that the read() method
628 supports omitting the size argument, and does not have a default
629 implementation that defers to readinto().
630
631 In addition, read(), readinto() and write() may raise
632 BlockingIOError if the underlying raw stream is in non-blocking
633 mode and not ready; unlike their raw counterparts, they will never
634 return None.
635
636 A typical implementation should not inherit from a RawIOBase
637 implementation, but wrap one.
638 """
639
Martin Panterccb2c0e2016-10-20 23:48:14 +0000640 def read(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300641 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000642
643 If the argument is omitted, None, or negative, reads and
644 returns all data until EOF.
645
646 If the argument is positive, and the underlying raw stream is
647 not 'interactive', multiple raw reads may be issued to satisfy
648 the byte count (unless EOF is reached first). But for
649 interactive raw streams (XXX and for pipes?), at most one raw
650 read will be issued, and a short result does not imply that
651 EOF is imminent.
652
653 Returns an empty bytes array on EOF.
654
655 Raises BlockingIOError if the underlying raw stream has no
656 data at the moment.
657 """
658 self._unsupported("read")
659
Martin Panterccb2c0e2016-10-20 23:48:14 +0000660 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300661 """Read up to size bytes with at most one read() system call,
662 where size is an int.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000663 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000664 self._unsupported("read1")
665
Raymond Hettinger3c940242011-01-12 23:39:31 +0000666 def readinto(self, b):
Martin Panter6bb91f32016-05-28 00:41:57 +0000667 """Read bytes into a pre-allocated bytes-like object b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000668
669 Like read(), this may issue multiple reads to the underlying raw
670 stream, unless the latter is 'interactive'.
671
Raymond Hettingercbb80892011-01-13 18:15:51 +0000672 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000673
674 Raises BlockingIOError if the underlying raw stream has no
675 data at the moment.
676 """
Benjamin Petersona96fea02014-06-22 14:17:44 -0700677
678 return self._readinto(b, read1=False)
679
680 def readinto1(self, b):
Martin Panter6bb91f32016-05-28 00:41:57 +0000681 """Read bytes into buffer *b*, using at most one system call
Benjamin Petersona96fea02014-06-22 14:17:44 -0700682
683 Returns an int representing the number of bytes read (0 for EOF).
684
685 Raises BlockingIOError if the underlying raw stream has no
686 data at the moment.
687 """
688
689 return self._readinto(b, read1=True)
690
691 def _readinto(self, b, read1):
692 if not isinstance(b, memoryview):
693 b = memoryview(b)
694 b = b.cast('B')
695
696 if read1:
697 data = self.read1(len(b))
698 else:
699 data = self.read(len(b))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000700 n = len(data)
Benjamin Petersona96fea02014-06-22 14:17:44 -0700701
702 b[:n] = data
703
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000704 return n
705
Raymond Hettinger3c940242011-01-12 23:39:31 +0000706 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000707 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000708
Martin Panter6bb91f32016-05-28 00:41:57 +0000709 Return the number of bytes written, which is always the length of b
710 in bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000711
712 Raises BlockingIOError if the buffer is full and the
713 underlying raw stream cannot accept more data at the moment.
714 """
715 self._unsupported("write")
716
Raymond Hettinger3c940242011-01-12 23:39:31 +0000717 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000718 """
719 Separate the underlying raw stream from the buffer and return it.
720
721 After the raw stream has been detached, the buffer is in an unusable
722 state.
723 """
724 self._unsupported("detach")
725
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000726io.BufferedIOBase.register(BufferedIOBase)
727
728
729class _BufferedIOMixin(BufferedIOBase):
730
731 """A mixin implementation of BufferedIOBase with an underlying raw stream.
732
733 This passes most requests on to the underlying raw stream. It
734 does *not* provide implementations of read(), readinto() or
735 write().
736 """
737
738 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000739 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000740
741 ### Positioning ###
742
743 def seek(self, pos, whence=0):
744 new_position = self.raw.seek(pos, whence)
745 if new_position < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200746 raise OSError("seek() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000747 return new_position
748
749 def tell(self):
750 pos = self.raw.tell()
751 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200752 raise OSError("tell() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000753 return pos
754
755 def truncate(self, pos=None):
756 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
757 # and a flush may be necessary to synch both views of the current
758 # file state.
759 self.flush()
760
761 if pos is None:
762 pos = self.tell()
763 # XXX: Should seek() be used, instead of passing the position
764 # XXX directly to truncate?
765 return self.raw.truncate(pos)
766
767 ### Flush and close ###
768
769 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000770 if self.closed:
Jim Fasarakis-Hilliard1e73dbb2017-03-26 23:59:08 +0300771 raise ValueError("flush on closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000772 self.raw.flush()
773
774 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000775 if self.raw is not None and not self.closed:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +0100776 try:
777 # may raise BlockingIOError or BrokenPipeError etc
778 self.flush()
779 finally:
780 self.raw.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000781
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000782 def detach(self):
783 if self.raw is None:
784 raise ValueError("raw stream already detached")
785 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000786 raw = self._raw
787 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000788 return raw
789
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000790 ### Inquiries ###
791
792 def seekable(self):
793 return self.raw.seekable()
794
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000795 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000796 def raw(self):
797 return self._raw
798
799 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000800 def closed(self):
801 return self.raw.closed
802
803 @property
804 def name(self):
805 return self.raw.name
806
807 @property
808 def mode(self):
809 return self.raw.mode
810
Antoine Pitrou243757e2010-11-05 21:15:39 +0000811 def __getstate__(self):
812 raise TypeError("can not serialize a '{0}' object"
813 .format(self.__class__.__name__))
814
Antoine Pitrou716c4442009-05-23 19:04:03 +0000815 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300816 modname = self.__class__.__module__
817 clsname = self.__class__.__qualname__
Antoine Pitrou716c4442009-05-23 19:04:03 +0000818 try:
819 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -0600820 except Exception:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300821 return "<{}.{}>".format(modname, clsname)
Antoine Pitrou716c4442009-05-23 19:04:03 +0000822 else:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300823 return "<{}.{} name={!r}>".format(modname, clsname, name)
Antoine Pitrou716c4442009-05-23 19:04:03 +0000824
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000825 ### Lower-level APIs ###
826
827 def fileno(self):
828 return self.raw.fileno()
829
830 def isatty(self):
831 return self.raw.isatty()
832
833
834class BytesIO(BufferedIOBase):
835
836 """Buffered I/O implementation using an in-memory bytes buffer."""
837
838 def __init__(self, initial_bytes=None):
839 buf = bytearray()
840 if initial_bytes is not None:
841 buf += initial_bytes
842 self._buffer = buf
843 self._pos = 0
844
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000845 def __getstate__(self):
846 if self.closed:
847 raise ValueError("__getstate__ on closed file")
848 return self.__dict__.copy()
849
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000850 def getvalue(self):
851 """Return the bytes value (contents) of the buffer
852 """
853 if self.closed:
854 raise ValueError("getvalue on closed file")
855 return bytes(self._buffer)
856
Antoine Pitrou972ee132010-09-06 18:48:21 +0000857 def getbuffer(self):
858 """Return a readable and writable view of the buffer.
859 """
Serhiy Storchakac057c382015-02-03 02:00:18 +0200860 if self.closed:
861 raise ValueError("getbuffer on closed file")
Antoine Pitrou972ee132010-09-06 18:48:21 +0000862 return memoryview(self._buffer)
863
Serhiy Storchakac057c382015-02-03 02:00:18 +0200864 def close(self):
865 self._buffer.clear()
866 super().close()
867
Martin Panterccb2c0e2016-10-20 23:48:14 +0000868 def read(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000869 if self.closed:
870 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300871 if size is None:
872 size = -1
Oren Milmande503602017-08-24 21:33:42 +0300873 else:
874 try:
875 size_index = size.__index__
876 except AttributeError:
877 raise TypeError(f"{size!r} is not an integer")
878 else:
879 size = size_index()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300880 if size < 0:
881 size = len(self._buffer)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000882 if len(self._buffer) <= self._pos:
883 return b""
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300884 newpos = min(len(self._buffer), self._pos + size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000885 b = self._buffer[self._pos : newpos]
886 self._pos = newpos
887 return bytes(b)
888
Martin Panterccb2c0e2016-10-20 23:48:14 +0000889 def read1(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000890 """This is the same as read.
891 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300892 return self.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000893
894 def write(self, b):
895 if self.closed:
896 raise ValueError("write to closed file")
897 if isinstance(b, str):
898 raise TypeError("can't write str to binary stream")
Martin Panter6bb91f32016-05-28 00:41:57 +0000899 with memoryview(b) as view:
900 n = view.nbytes # Size of any bytes-like object
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000901 if n == 0:
902 return 0
903 pos = self._pos
904 if pos > len(self._buffer):
905 # Inserts null bytes between the current end of the file
906 # and the new write position.
907 padding = b'\x00' * (pos - len(self._buffer))
908 self._buffer += padding
909 self._buffer[pos:pos + n] = b
910 self._pos += n
911 return n
912
913 def seek(self, pos, whence=0):
914 if self.closed:
915 raise ValueError("seek on closed file")
916 try:
Oren Milmande503602017-08-24 21:33:42 +0300917 pos_index = pos.__index__
918 except AttributeError:
919 raise TypeError(f"{pos!r} is not an integer")
920 else:
921 pos = pos_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000922 if whence == 0:
923 if pos < 0:
924 raise ValueError("negative seek position %r" % (pos,))
925 self._pos = pos
926 elif whence == 1:
927 self._pos = max(0, self._pos + pos)
928 elif whence == 2:
929 self._pos = max(0, len(self._buffer) + pos)
930 else:
Jesus Cea94363612012-06-22 18:32:07 +0200931 raise ValueError("unsupported whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000932 return self._pos
933
934 def tell(self):
935 if self.closed:
936 raise ValueError("tell on closed file")
937 return self._pos
938
939 def truncate(self, pos=None):
940 if self.closed:
941 raise ValueError("truncate on closed file")
942 if pos is None:
943 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000944 else:
945 try:
Oren Milmande503602017-08-24 21:33:42 +0300946 pos_index = pos.__index__
947 except AttributeError:
948 raise TypeError(f"{pos!r} is not an integer")
949 else:
950 pos = pos_index()
Florent Xiclunab14930c2010-03-13 15:26:44 +0000951 if pos < 0:
952 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000953 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000954 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000955
956 def readable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200957 if self.closed:
958 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000959 return True
960
961 def writable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200962 if self.closed:
963 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000964 return True
965
966 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200967 if self.closed:
968 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000969 return True
970
971
972class BufferedReader(_BufferedIOMixin):
973
974 """BufferedReader(raw[, buffer_size])
975
976 A buffer for a readable, sequential BaseRawIO object.
977
978 The constructor creates a BufferedReader for the given readable raw
979 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
980 is used.
981 """
982
983 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
984 """Create a new buffered reader using the given readable raw IO object.
985 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000986 if not raw.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200987 raise OSError('"raw" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000988
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000989 _BufferedIOMixin.__init__(self, raw)
990 if buffer_size <= 0:
991 raise ValueError("invalid buffer size")
992 self.buffer_size = buffer_size
993 self._reset_read_buf()
994 self._read_lock = Lock()
995
Martin Panter754aab22016-03-31 07:21:56 +0000996 def readable(self):
997 return self.raw.readable()
998
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000999 def _reset_read_buf(self):
1000 self._read_buf = b""
1001 self._read_pos = 0
1002
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001003 def read(self, size=None):
1004 """Read size bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001005
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001006 Returns exactly size bytes of data unless the underlying raw IO
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001007 stream reaches EOF or if the call would block in non-blocking
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001008 mode. If size is negative, read until EOF or until read() would
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001009 block.
1010 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001011 if size is not None and size < -1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001012 raise ValueError("invalid number of bytes to read")
1013 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001014 return self._read_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001015
1016 def _read_unlocked(self, n=None):
1017 nodata_val = b""
1018 empty_values = (b"", None)
1019 buf = self._read_buf
1020 pos = self._read_pos
1021
1022 # Special case for when the number of bytes to read is unspecified.
1023 if n is None or n == -1:
1024 self._reset_read_buf()
Victor Stinnerb57f1082011-05-26 00:19:38 +02001025 if hasattr(self.raw, 'readall'):
1026 chunk = self.raw.readall()
1027 if chunk is None:
1028 return buf[pos:] or None
1029 else:
1030 return buf[pos:] + chunk
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001031 chunks = [buf[pos:]] # Strip the consumed bytes.
1032 current_size = 0
1033 while True:
1034 # Read until EOF or until read() would block.
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001035 chunk = self.raw.read()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001036 if chunk in empty_values:
1037 nodata_val = chunk
1038 break
1039 current_size += len(chunk)
1040 chunks.append(chunk)
1041 return b"".join(chunks) or nodata_val
1042
1043 # The number of bytes to read is specified, return at most n bytes.
1044 avail = len(buf) - pos # Length of the available buffered data.
1045 if n <= avail:
1046 # Fast path: the data to read is fully buffered.
1047 self._read_pos += n
1048 return buf[pos:pos+n]
1049 # Slow path: read from the stream until enough bytes are read,
1050 # or until an EOF occurs or until read() would block.
1051 chunks = [buf[pos:]]
1052 wanted = max(self.buffer_size, n)
1053 while avail < n:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001054 chunk = self.raw.read(wanted)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001055 if chunk in empty_values:
1056 nodata_val = chunk
1057 break
1058 avail += len(chunk)
1059 chunks.append(chunk)
Martin Pantere26da7c2016-06-02 10:07:09 +00001060 # n is more than avail only when an EOF occurred or when
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001061 # read() would have blocked.
1062 n = min(n, avail)
1063 out = b"".join(chunks)
1064 self._read_buf = out[n:] # Save the extra data in the buffer.
1065 self._read_pos = 0
1066 return out[:n] if out else nodata_val
1067
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001068 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001069 """Returns buffered bytes without advancing the position.
1070
1071 The argument indicates a desired minimal number of bytes; we
1072 do at most one raw read to satisfy it. We never return more
1073 than self.buffer_size.
1074 """
1075 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001076 return self._peek_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001077
1078 def _peek_unlocked(self, n=0):
1079 want = min(n, self.buffer_size)
1080 have = len(self._read_buf) - self._read_pos
1081 if have < want or have <= 0:
1082 to_read = self.buffer_size - have
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001083 current = self.raw.read(to_read)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001084 if current:
1085 self._read_buf = self._read_buf[self._read_pos:] + current
1086 self._read_pos = 0
1087 return self._read_buf[self._read_pos:]
1088
Martin Panterccb2c0e2016-10-20 23:48:14 +00001089 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001090 """Reads up to size bytes, with at most one read() system call."""
1091 # Returns up to size bytes. If at least one byte is buffered, we
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001092 # only return buffered bytes. Otherwise, we do one raw read.
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001093 if size < 0:
Martin Panterccb2c0e2016-10-20 23:48:14 +00001094 size = self.buffer_size
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001095 if size == 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001096 return b""
1097 with self._read_lock:
1098 self._peek_unlocked(1)
1099 return self._read_unlocked(
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001100 min(size, len(self._read_buf) - self._read_pos))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001101
Benjamin Petersona96fea02014-06-22 14:17:44 -07001102 # Implementing readinto() and readinto1() is not strictly necessary (we
1103 # could rely on the base class that provides an implementation in terms of
1104 # read() and read1()). We do it anyway to keep the _pyio implementation
1105 # similar to the io implementation (which implements the methods for
1106 # performance reasons).
1107 def _readinto(self, buf, read1):
1108 """Read data into *buf* with at most one system call."""
1109
Benjamin Petersona96fea02014-06-22 14:17:44 -07001110 # Need to create a memoryview object of type 'b', otherwise
1111 # we may not be able to assign bytes to it, and slicing it
1112 # would create a new object.
1113 if not isinstance(buf, memoryview):
1114 buf = memoryview(buf)
Martin Panter6bb91f32016-05-28 00:41:57 +00001115 if buf.nbytes == 0:
1116 return 0
Benjamin Petersona96fea02014-06-22 14:17:44 -07001117 buf = buf.cast('B')
1118
1119 written = 0
1120 with self._read_lock:
1121 while written < len(buf):
1122
1123 # First try to read from internal buffer
1124 avail = min(len(self._read_buf) - self._read_pos, len(buf))
1125 if avail:
1126 buf[written:written+avail] = \
1127 self._read_buf[self._read_pos:self._read_pos+avail]
1128 self._read_pos += avail
1129 written += avail
1130 if written == len(buf):
1131 break
1132
1133 # If remaining space in callers buffer is larger than
1134 # internal buffer, read directly into callers buffer
1135 if len(buf) - written > self.buffer_size:
1136 n = self.raw.readinto(buf[written:])
1137 if not n:
1138 break # eof
1139 written += n
1140
1141 # Otherwise refill internal buffer - unless we're
1142 # in read1 mode and already got some data
1143 elif not (read1 and written):
1144 if not self._peek_unlocked(1):
1145 break # eof
1146
1147 # In readinto1 mode, return as soon as we have some data
1148 if read1 and written:
1149 break
1150
1151 return written
1152
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001153 def tell(self):
1154 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1155
1156 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001157 if whence not in valid_seek_flags:
Jesus Cea990eff02012-04-26 17:05:31 +02001158 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001159 with self._read_lock:
1160 if whence == 1:
1161 pos -= len(self._read_buf) - self._read_pos
1162 pos = _BufferedIOMixin.seek(self, pos, whence)
1163 self._reset_read_buf()
1164 return pos
1165
1166class BufferedWriter(_BufferedIOMixin):
1167
1168 """A buffer for a writeable sequential RawIO object.
1169
1170 The constructor creates a BufferedWriter for the given writeable raw
1171 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001172 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001173 """
1174
Florent Xicluna109d5732012-07-07 17:03:22 +02001175 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001176 if not raw.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001177 raise OSError('"raw" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001178
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001179 _BufferedIOMixin.__init__(self, raw)
1180 if buffer_size <= 0:
1181 raise ValueError("invalid buffer size")
1182 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001183 self._write_buf = bytearray()
1184 self._write_lock = Lock()
Neil Schemenauer0a1ff242017-09-22 10:17:30 -07001185 _register_writer(self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001186
Martin Panter754aab22016-03-31 07:21:56 +00001187 def writable(self):
1188 return self.raw.writable()
1189
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001190 def write(self, b):
1191 if self.closed:
1192 raise ValueError("write to closed file")
1193 if isinstance(b, str):
1194 raise TypeError("can't write str to binary stream")
1195 with self._write_lock:
1196 # XXX we can implement some more tricks to try and avoid
1197 # partial writes
1198 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001199 # We're full, so let's pre-flush the buffer. (This may
1200 # raise BlockingIOError with characters_written == 0.)
1201 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001202 before = len(self._write_buf)
1203 self._write_buf.extend(b)
1204 written = len(self._write_buf) - before
1205 if len(self._write_buf) > self.buffer_size:
1206 try:
1207 self._flush_unlocked()
1208 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001209 if len(self._write_buf) > self.buffer_size:
1210 # We've hit the buffer_size. We have to accept a partial
1211 # write and cut back our buffer.
1212 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001213 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001214 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001215 raise BlockingIOError(e.errno, e.strerror, written)
1216 return written
1217
1218 def truncate(self, pos=None):
1219 with self._write_lock:
1220 self._flush_unlocked()
1221 if pos is None:
1222 pos = self.raw.tell()
1223 return self.raw.truncate(pos)
1224
1225 def flush(self):
1226 with self._write_lock:
1227 self._flush_unlocked()
1228
1229 def _flush_unlocked(self):
1230 if self.closed:
Jim Fasarakis-Hilliard1e73dbb2017-03-26 23:59:08 +03001231 raise ValueError("flush on closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001232 while self._write_buf:
1233 try:
1234 n = self.raw.write(self._write_buf)
1235 except BlockingIOError:
1236 raise RuntimeError("self.raw should implement RawIOBase: it "
1237 "should not raise BlockingIOError")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001238 if n is None:
1239 raise BlockingIOError(
1240 errno.EAGAIN,
1241 "write could not complete without blocking", 0)
1242 if n > len(self._write_buf) or n < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001243 raise OSError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001244 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001245
1246 def tell(self):
1247 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1248
1249 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001250 if whence not in valid_seek_flags:
1251 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001252 with self._write_lock:
1253 self._flush_unlocked()
1254 return _BufferedIOMixin.seek(self, pos, whence)
1255
1256
1257class BufferedRWPair(BufferedIOBase):
1258
1259 """A buffered reader and writer object together.
1260
1261 A buffered reader object and buffered writer object put together to
1262 form a sequential IO object that can read and write. This is typically
1263 used with a socket or two-way pipe.
1264
1265 reader and writer are RawIOBase objects that are readable and
1266 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001267 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001268 """
1269
1270 # XXX The usefulness of this (compared to having two separate IO
1271 # objects) is questionable.
1272
Florent Xicluna109d5732012-07-07 17:03:22 +02001273 def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001274 """Constructor.
1275
1276 The arguments are two RawIO instances.
1277 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001278 if not reader.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001279 raise OSError('"reader" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001280
1281 if not writer.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001282 raise OSError('"writer" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001283
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001284 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001285 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001286
Martin Panterccb2c0e2016-10-20 23:48:14 +00001287 def read(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001288 if size is None:
1289 size = -1
1290 return self.reader.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001291
1292 def readinto(self, b):
1293 return self.reader.readinto(b)
1294
1295 def write(self, b):
1296 return self.writer.write(b)
1297
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001298 def peek(self, size=0):
1299 return self.reader.peek(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001300
Martin Panterccb2c0e2016-10-20 23:48:14 +00001301 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001302 return self.reader.read1(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001303
Benjamin Petersona96fea02014-06-22 14:17:44 -07001304 def readinto1(self, b):
1305 return self.reader.readinto1(b)
1306
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001307 def readable(self):
1308 return self.reader.readable()
1309
1310 def writable(self):
1311 return self.writer.writable()
1312
1313 def flush(self):
1314 return self.writer.flush()
1315
1316 def close(self):
Serhiy Storchaka7665be62015-03-24 23:21:57 +02001317 try:
1318 self.writer.close()
1319 finally:
1320 self.reader.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001321
1322 def isatty(self):
1323 return self.reader.isatty() or self.writer.isatty()
1324
1325 @property
1326 def closed(self):
1327 return self.writer.closed
1328
1329
1330class BufferedRandom(BufferedWriter, BufferedReader):
1331
1332 """A buffered interface to random access streams.
1333
1334 The constructor creates a reader and writer for a seekable stream,
1335 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001336 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001337 """
1338
Florent Xicluna109d5732012-07-07 17:03:22 +02001339 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001340 raw._checkSeekable()
1341 BufferedReader.__init__(self, raw, buffer_size)
Florent Xicluna109d5732012-07-07 17:03:22 +02001342 BufferedWriter.__init__(self, raw, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001343
1344 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001345 if whence not in valid_seek_flags:
1346 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001347 self.flush()
1348 if self._read_buf:
1349 # Undo read ahead.
1350 with self._read_lock:
1351 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1352 # First do the raw seek, then empty the read buffer, so that
1353 # if the raw seek fails, we don't lose buffered data forever.
1354 pos = self.raw.seek(pos, whence)
1355 with self._read_lock:
1356 self._reset_read_buf()
1357 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001358 raise OSError("seek() returned invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001359 return pos
1360
1361 def tell(self):
1362 if self._write_buf:
1363 return BufferedWriter.tell(self)
1364 else:
1365 return BufferedReader.tell(self)
1366
1367 def truncate(self, pos=None):
1368 if pos is None:
1369 pos = self.tell()
1370 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001371 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001372
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001373 def read(self, size=None):
1374 if size is None:
1375 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001376 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001377 return BufferedReader.read(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001378
1379 def readinto(self, b):
1380 self.flush()
1381 return BufferedReader.readinto(self, b)
1382
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001383 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001384 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001385 return BufferedReader.peek(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001386
Martin Panterccb2c0e2016-10-20 23:48:14 +00001387 def read1(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001388 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001389 return BufferedReader.read1(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001390
Benjamin Petersona96fea02014-06-22 14:17:44 -07001391 def readinto1(self, b):
1392 self.flush()
1393 return BufferedReader.readinto1(self, b)
1394
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001395 def write(self, b):
1396 if self._read_buf:
1397 # Undo readahead
1398 with self._read_lock:
1399 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1400 self._reset_read_buf()
1401 return BufferedWriter.write(self, b)
1402
1403
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001404class FileIO(RawIOBase):
1405 _fd = -1
1406 _created = False
1407 _readable = False
1408 _writable = False
1409 _appending = False
1410 _seekable = None
1411 _closefd = True
1412
1413 def __init__(self, file, mode='r', closefd=True, opener=None):
1414 """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
1415 writing, exclusive creation or appending. The file will be created if it
1416 doesn't exist when opened for writing or appending; it will be truncated
1417 when opened for writing. A FileExistsError will be raised if it already
1418 exists when opened for creating. Opening a file for creating implies
1419 writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode
1420 to allow simultaneous reading and writing. A custom opener can be used by
1421 passing a callable as *opener*. The underlying file descriptor for the file
1422 object is then obtained by calling opener with (*name*, *flags*).
1423 *opener* must return an open file descriptor (passing os.open as *opener*
1424 results in functionality similar to passing None).
1425 """
1426 if self._fd >= 0:
1427 # Have to close the existing file first.
1428 try:
1429 if self._closefd:
1430 os.close(self._fd)
1431 finally:
1432 self._fd = -1
1433
1434 if isinstance(file, float):
1435 raise TypeError('integer argument expected, got float')
1436 if isinstance(file, int):
1437 fd = file
1438 if fd < 0:
1439 raise ValueError('negative file descriptor')
1440 else:
1441 fd = -1
1442
1443 if not isinstance(mode, str):
1444 raise TypeError('invalid mode: %s' % (mode,))
1445 if not set(mode) <= set('xrwab+'):
1446 raise ValueError('invalid mode: %s' % (mode,))
1447 if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1:
1448 raise ValueError('Must have exactly one of create/read/write/append '
1449 'mode and at most one plus')
1450
1451 if 'x' in mode:
1452 self._created = True
1453 self._writable = True
1454 flags = os.O_EXCL | os.O_CREAT
1455 elif 'r' in mode:
1456 self._readable = True
1457 flags = 0
1458 elif 'w' in mode:
1459 self._writable = True
1460 flags = os.O_CREAT | os.O_TRUNC
1461 elif 'a' in mode:
1462 self._writable = True
1463 self._appending = True
1464 flags = os.O_APPEND | os.O_CREAT
1465
1466 if '+' in mode:
1467 self._readable = True
1468 self._writable = True
1469
1470 if self._readable and self._writable:
1471 flags |= os.O_RDWR
1472 elif self._readable:
1473 flags |= os.O_RDONLY
1474 else:
1475 flags |= os.O_WRONLY
1476
1477 flags |= getattr(os, 'O_BINARY', 0)
1478
1479 noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or
1480 getattr(os, 'O_CLOEXEC', 0))
1481 flags |= noinherit_flag
1482
1483 owned_fd = None
1484 try:
1485 if fd < 0:
1486 if not closefd:
1487 raise ValueError('Cannot use closefd=False with file name')
1488 if opener is None:
1489 fd = os.open(file, flags, 0o666)
1490 else:
1491 fd = opener(file, flags)
1492 if not isinstance(fd, int):
1493 raise TypeError('expected integer from opener')
1494 if fd < 0:
1495 raise OSError('Negative file descriptor')
1496 owned_fd = fd
1497 if not noinherit_flag:
1498 os.set_inheritable(fd, False)
1499
1500 self._closefd = closefd
1501 fdfstat = os.fstat(fd)
1502 try:
1503 if stat.S_ISDIR(fdfstat.st_mode):
1504 raise IsADirectoryError(errno.EISDIR,
1505 os.strerror(errno.EISDIR), file)
1506 except AttributeError:
1507 # Ignore the AttribueError if stat.S_ISDIR or errno.EISDIR
1508 # don't exist.
1509 pass
1510 self._blksize = getattr(fdfstat, 'st_blksize', 0)
1511 if self._blksize <= 1:
1512 self._blksize = DEFAULT_BUFFER_SIZE
1513
1514 if _setmode:
1515 # don't translate newlines (\r\n <=> \n)
1516 _setmode(fd, os.O_BINARY)
1517
1518 self.name = file
1519 if self._appending:
1520 # For consistent behaviour, we explicitly seek to the
1521 # end of file (otherwise, it might be done only on the
1522 # first write()).
1523 os.lseek(fd, 0, SEEK_END)
1524 except:
1525 if owned_fd is not None:
1526 os.close(owned_fd)
1527 raise
1528 self._fd = fd
1529
1530 def __del__(self):
1531 if self._fd >= 0 and self._closefd and not self.closed:
1532 import warnings
1533 warnings.warn('unclosed file %r' % (self,), ResourceWarning,
Victor Stinnere19558a2016-03-23 00:28:08 +01001534 stacklevel=2, source=self)
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001535 self.close()
1536
1537 def __getstate__(self):
1538 raise TypeError("cannot serialize '%s' object", self.__class__.__name__)
1539
1540 def __repr__(self):
1541 class_name = '%s.%s' % (self.__class__.__module__,
1542 self.__class__.__qualname__)
1543 if self.closed:
1544 return '<%s [closed]>' % class_name
1545 try:
1546 name = self.name
1547 except AttributeError:
1548 return ('<%s fd=%d mode=%r closefd=%r>' %
1549 (class_name, self._fd, self.mode, self._closefd))
1550 else:
1551 return ('<%s name=%r mode=%r closefd=%r>' %
1552 (class_name, name, self.mode, self._closefd))
1553
1554 def _checkReadable(self):
1555 if not self._readable:
1556 raise UnsupportedOperation('File not open for reading')
1557
1558 def _checkWritable(self, msg=None):
1559 if not self._writable:
1560 raise UnsupportedOperation('File not open for writing')
1561
1562 def read(self, size=None):
1563 """Read at most size bytes, returned as bytes.
1564
1565 Only makes one system call, so less data may be returned than requested
1566 In non-blocking mode, returns None if no data is available.
1567 Return an empty bytes object at EOF.
1568 """
1569 self._checkClosed()
1570 self._checkReadable()
1571 if size is None or size < 0:
1572 return self.readall()
1573 try:
1574 return os.read(self._fd, size)
1575 except BlockingIOError:
1576 return None
1577
1578 def readall(self):
1579 """Read all data from the file, returned as bytes.
1580
1581 In non-blocking mode, returns as much as is immediately available,
1582 or None if no data is available. Return an empty bytes object at EOF.
1583 """
1584 self._checkClosed()
1585 self._checkReadable()
1586 bufsize = DEFAULT_BUFFER_SIZE
1587 try:
1588 pos = os.lseek(self._fd, 0, SEEK_CUR)
1589 end = os.fstat(self._fd).st_size
1590 if end >= pos:
1591 bufsize = end - pos + 1
1592 except OSError:
1593 pass
1594
1595 result = bytearray()
1596 while True:
1597 if len(result) >= bufsize:
1598 bufsize = len(result)
1599 bufsize += max(bufsize, DEFAULT_BUFFER_SIZE)
1600 n = bufsize - len(result)
1601 try:
1602 chunk = os.read(self._fd, n)
1603 except BlockingIOError:
1604 if result:
1605 break
1606 return None
1607 if not chunk: # reached the end of the file
1608 break
1609 result += chunk
1610
1611 return bytes(result)
1612
1613 def readinto(self, b):
1614 """Same as RawIOBase.readinto()."""
1615 m = memoryview(b).cast('B')
1616 data = self.read(len(m))
1617 n = len(data)
1618 m[:n] = data
1619 return n
1620
1621 def write(self, b):
1622 """Write bytes b to file, return number written.
1623
1624 Only makes one system call, so not all of the data may be written.
1625 The number of bytes actually written is returned. In non-blocking mode,
1626 returns None if the write would block.
1627 """
1628 self._checkClosed()
1629 self._checkWritable()
1630 try:
1631 return os.write(self._fd, b)
1632 except BlockingIOError:
1633 return None
1634
1635 def seek(self, pos, whence=SEEK_SET):
1636 """Move to new file position.
1637
1638 Argument offset is a byte count. Optional argument whence defaults to
1639 SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
1640 are SEEK_CUR or 1 (move relative to current position, positive or negative),
1641 and SEEK_END or 2 (move relative to end of file, usually negative, although
1642 many platforms allow seeking beyond the end of a file).
1643
1644 Note that not all file objects are seekable.
1645 """
1646 if isinstance(pos, float):
1647 raise TypeError('an integer is required')
1648 self._checkClosed()
1649 return os.lseek(self._fd, pos, whence)
1650
1651 def tell(self):
1652 """tell() -> int. Current file position.
1653
1654 Can raise OSError for non seekable files."""
1655 self._checkClosed()
1656 return os.lseek(self._fd, 0, SEEK_CUR)
1657
1658 def truncate(self, size=None):
1659 """Truncate the file to at most size bytes.
1660
1661 Size defaults to the current file position, as returned by tell().
1662 The current file position is changed to the value of size.
1663 """
1664 self._checkClosed()
1665 self._checkWritable()
1666 if size is None:
1667 size = self.tell()
1668 os.ftruncate(self._fd, size)
1669 return size
1670
1671 def close(self):
1672 """Close the file.
1673
1674 A closed file cannot be used for further I/O operations. close() may be
1675 called more than once without error.
1676 """
1677 if not self.closed:
1678 try:
1679 if self._closefd:
1680 os.close(self._fd)
1681 finally:
1682 super().close()
1683
1684 def seekable(self):
1685 """True if file supports random-access."""
1686 self._checkClosed()
1687 if self._seekable is None:
1688 try:
1689 self.tell()
1690 except OSError:
1691 self._seekable = False
1692 else:
1693 self._seekable = True
1694 return self._seekable
1695
1696 def readable(self):
1697 """True if file was opened in a read mode."""
1698 self._checkClosed()
1699 return self._readable
1700
1701 def writable(self):
1702 """True if file was opened in a write mode."""
1703 self._checkClosed()
1704 return self._writable
1705
1706 def fileno(self):
1707 """Return the underlying file descriptor (an integer)."""
1708 self._checkClosed()
1709 return self._fd
1710
1711 def isatty(self):
1712 """True if the file is connected to a TTY device."""
1713 self._checkClosed()
1714 return os.isatty(self._fd)
1715
1716 @property
1717 def closefd(self):
1718 """True if the file descriptor will be closed by close()."""
1719 return self._closefd
1720
1721 @property
1722 def mode(self):
1723 """String giving the file mode"""
1724 if self._created:
1725 if self._readable:
1726 return 'xb+'
1727 else:
1728 return 'xb'
1729 elif self._appending:
1730 if self._readable:
1731 return 'ab+'
1732 else:
1733 return 'ab'
1734 elif self._readable:
1735 if self._writable:
1736 return 'rb+'
1737 else:
1738 return 'rb'
1739 else:
1740 return 'wb'
1741
1742
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001743class TextIOBase(IOBase):
1744
1745 """Base class for text I/O.
1746
1747 This class provides a character and line based interface to stream
1748 I/O. There is no readinto method because Python's character strings
1749 are immutable. There is no public constructor.
1750 """
1751
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001752 def read(self, size=-1):
1753 """Read at most size characters from stream, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001754
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001755 Read from underlying buffer until we have size characters or we hit EOF.
1756 If size is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001757
1758 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001759 """
1760 self._unsupported("read")
1761
Raymond Hettinger3c940242011-01-12 23:39:31 +00001762 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001763 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001764 self._unsupported("write")
1765
Georg Brandl4d73b572011-01-13 07:13:06 +00001766 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001767 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001768 self._unsupported("truncate")
1769
Raymond Hettinger3c940242011-01-12 23:39:31 +00001770 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001771 """Read until newline or EOF.
1772
1773 Returns an empty string if EOF is hit immediately.
1774 """
1775 self._unsupported("readline")
1776
Raymond Hettinger3c940242011-01-12 23:39:31 +00001777 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001778 """
1779 Separate the underlying buffer from the TextIOBase and return it.
1780
1781 After the underlying buffer has been detached, the TextIO is in an
1782 unusable state.
1783 """
1784 self._unsupported("detach")
1785
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001786 @property
1787 def encoding(self):
1788 """Subclasses should override."""
1789 return None
1790
1791 @property
1792 def newlines(self):
1793 """Line endings translated so far.
1794
1795 Only line endings translated during reading are considered.
1796
1797 Subclasses should override.
1798 """
1799 return None
1800
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001801 @property
1802 def errors(self):
1803 """Error setting of the decoder or encoder.
1804
1805 Subclasses should override."""
1806 return None
1807
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001808io.TextIOBase.register(TextIOBase)
1809
1810
1811class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1812 r"""Codec used when reading a file in universal newlines mode. It wraps
1813 another incremental decoder, translating \r\n and \r into \n. It also
1814 records the types of newlines encountered. When used with
1815 translate=False, it ensures that the newline sequence is returned in
1816 one piece.
1817 """
1818 def __init__(self, decoder, translate, errors='strict'):
1819 codecs.IncrementalDecoder.__init__(self, errors=errors)
1820 self.translate = translate
1821 self.decoder = decoder
1822 self.seennl = 0
1823 self.pendingcr = False
1824
1825 def decode(self, input, final=False):
1826 # decode input (with the eventual \r from a previous pass)
1827 if self.decoder is None:
1828 output = input
1829 else:
1830 output = self.decoder.decode(input, final=final)
1831 if self.pendingcr and (output or final):
1832 output = "\r" + output
1833 self.pendingcr = False
1834
1835 # retain last \r even when not translating data:
1836 # then readline() is sure to get \r\n in one pass
1837 if output.endswith("\r") and not final:
1838 output = output[:-1]
1839 self.pendingcr = True
1840
1841 # Record which newlines are read
1842 crlf = output.count('\r\n')
1843 cr = output.count('\r') - crlf
1844 lf = output.count('\n') - crlf
1845 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1846 | (crlf and self._CRLF)
1847
1848 if self.translate:
1849 if crlf:
1850 output = output.replace("\r\n", "\n")
1851 if cr:
1852 output = output.replace("\r", "\n")
1853
1854 return output
1855
1856 def getstate(self):
1857 if self.decoder is None:
1858 buf = b""
1859 flag = 0
1860 else:
1861 buf, flag = self.decoder.getstate()
1862 flag <<= 1
1863 if self.pendingcr:
1864 flag |= 1
1865 return buf, flag
1866
1867 def setstate(self, state):
1868 buf, flag = state
1869 self.pendingcr = bool(flag & 1)
1870 if self.decoder is not None:
1871 self.decoder.setstate((buf, flag >> 1))
1872
1873 def reset(self):
1874 self.seennl = 0
1875 self.pendingcr = False
1876 if self.decoder is not None:
1877 self.decoder.reset()
1878
1879 _LF = 1
1880 _CR = 2
1881 _CRLF = 4
1882
1883 @property
1884 def newlines(self):
1885 return (None,
1886 "\n",
1887 "\r",
1888 ("\r", "\n"),
1889 "\r\n",
1890 ("\n", "\r\n"),
1891 ("\r", "\r\n"),
1892 ("\r", "\n", "\r\n")
1893 )[self.seennl]
1894
1895
1896class TextIOWrapper(TextIOBase):
1897
1898 r"""Character and line based layer over a BufferedIOBase object, buffer.
1899
1900 encoding gives the name of the encoding that the stream will be
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001901 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001902
1903 errors determines the strictness of encoding and decoding (see the
1904 codecs.register) and defaults to "strict".
1905
1906 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1907 handling of line endings. If it is None, universal newlines is
1908 enabled. With this enabled, on input, the lines endings '\n', '\r',
1909 or '\r\n' are translated to '\n' before being returned to the
1910 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001911 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001912 legal values, that newline becomes the newline when the file is read
1913 and it is returned untranslated. On output, '\n' is converted to the
1914 newline.
1915
1916 If line_buffering is True, a call to flush is implied when a call to
1917 write contains a newline character.
1918 """
1919
1920 _CHUNK_SIZE = 2048
1921
Andrew Svetlov4e9e9c12012-08-13 16:09:54 +03001922 # The write_through argument has no effect here since this
1923 # implementation always writes through. The argument is present only
1924 # so that the signature can match the signature of the C version.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001925 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001926 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001927 if newline is not None and not isinstance(newline, str):
1928 raise TypeError("illegal newline type: %r" % (type(newline),))
1929 if newline not in (None, "", "\n", "\r", "\r\n"):
1930 raise ValueError("illegal newline value: %r" % (newline,))
1931 if encoding is None:
1932 try:
1933 encoding = os.device_encoding(buffer.fileno())
1934 except (AttributeError, UnsupportedOperation):
1935 pass
1936 if encoding is None:
1937 try:
1938 import locale
Brett Cannoncd171c82013-07-04 17:43:24 -04001939 except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001940 # Importing locale may fail if Python is being built
1941 encoding = "ascii"
1942 else:
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001943 encoding = locale.getpreferredencoding(False)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001944
1945 if not isinstance(encoding, str):
1946 raise ValueError("invalid encoding: %r" % encoding)
1947
Nick Coghlana9b15242014-02-04 22:11:18 +10001948 if not codecs.lookup(encoding)._is_text_encoding:
1949 msg = ("%r is not a text encoding; "
1950 "use codecs.open() to handle arbitrary codecs")
1951 raise LookupError(msg % encoding)
1952
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001953 if errors is None:
1954 errors = "strict"
1955 else:
1956 if not isinstance(errors, str):
1957 raise ValueError("invalid errors: %r" % errors)
1958
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001959 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001960 self._encoding = encoding
1961 self._errors = errors
1962 self._readuniversal = not newline
1963 self._readtranslate = newline is None
1964 self._readnl = newline
1965 self._writetranslate = newline != ''
1966 self._writenl = newline or os.linesep
1967 self._encoder = None
1968 self._decoder = None
1969 self._decoded_chars = '' # buffer for text returned from decoder
1970 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1971 self._snapshot = None # info for reconstructing decoder state
1972 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001973 self._has_read1 = hasattr(self.buffer, 'read1')
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001974 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001975
Antoine Pitroue4501852009-05-14 18:55:55 +00001976 if self._seekable and self.writable():
1977 position = self.buffer.tell()
1978 if position != 0:
1979 try:
1980 self._get_encoder().setstate(0)
1981 except LookupError:
1982 # Sometimes the encoder doesn't exist
1983 pass
1984
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02001985 self._configure(line_buffering, write_through)
1986
1987 def _configure(self, line_buffering=False, write_through=False):
1988 self._line_buffering = line_buffering
1989 self._write_through = write_through
1990
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001991 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1992 # where dec_flags is the second (integer) item of the decoder state
1993 # and next_input is the chunk of input bytes that comes next after the
1994 # snapshot point. We use this to reconstruct decoder states in tell().
1995
1996 # Naming convention:
1997 # - "bytes_..." for integer variables that count input bytes
1998 # - "chars_..." for integer variables that count decoded characters
1999
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00002000 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +03002001 result = "<{}.{}".format(self.__class__.__module__,
2002 self.__class__.__qualname__)
Antoine Pitrou716c4442009-05-23 19:04:03 +00002003 try:
2004 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -06002005 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002006 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00002007 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002008 result += " name={0!r}".format(name)
2009 try:
2010 mode = self.mode
Benjamin Peterson10e76b62014-12-21 20:51:50 -06002011 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002012 pass
2013 else:
2014 result += " mode={0!r}".format(mode)
2015 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00002016
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002017 @property
2018 def encoding(self):
2019 return self._encoding
2020
2021 @property
2022 def errors(self):
2023 return self._errors
2024
2025 @property
2026 def line_buffering(self):
2027 return self._line_buffering
2028
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002029 @property
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002030 def write_through(self):
2031 return self._write_through
2032
2033 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002034 def buffer(self):
2035 return self._buffer
2036
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002037 def reconfigure(self, *, line_buffering=None, write_through=None):
2038 """Reconfigure the text stream with new parameters.
2039
2040 This also flushes the stream.
2041 """
2042 if line_buffering is None:
2043 line_buffering = self.line_buffering
2044 if write_through is None:
2045 write_through = self.write_through
2046 self.flush()
2047 self._configure(line_buffering, write_through)
2048
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002049 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02002050 if self.closed:
2051 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002052 return self._seekable
2053
2054 def readable(self):
2055 return self.buffer.readable()
2056
2057 def writable(self):
2058 return self.buffer.writable()
2059
2060 def flush(self):
2061 self.buffer.flush()
2062 self._telling = self._seekable
2063
2064 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00002065 if self.buffer is not None and not self.closed:
Benjamin Peterson68623612012-12-20 11:53:11 -06002066 try:
2067 self.flush()
2068 finally:
2069 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002070
2071 @property
2072 def closed(self):
2073 return self.buffer.closed
2074
2075 @property
2076 def name(self):
2077 return self.buffer.name
2078
2079 def fileno(self):
2080 return self.buffer.fileno()
2081
2082 def isatty(self):
2083 return self.buffer.isatty()
2084
Raymond Hettinger00fa0392011-01-13 02:52:26 +00002085 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00002086 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002087 if self.closed:
2088 raise ValueError("write to closed file")
2089 if not isinstance(s, str):
2090 raise TypeError("can't write %s to text stream" %
2091 s.__class__.__name__)
2092 length = len(s)
2093 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
2094 if haslf and self._writetranslate and self._writenl != "\n":
2095 s = s.replace("\n", self._writenl)
2096 encoder = self._encoder or self._get_encoder()
2097 # XXX What if we were just reading?
2098 b = encoder.encode(s)
2099 self.buffer.write(b)
2100 if self._line_buffering and (haslf or "\r" in s):
2101 self.flush()
2102 self._snapshot = None
2103 if self._decoder:
2104 self._decoder.reset()
2105 return length
2106
2107 def _get_encoder(self):
2108 make_encoder = codecs.getincrementalencoder(self._encoding)
2109 self._encoder = make_encoder(self._errors)
2110 return self._encoder
2111
2112 def _get_decoder(self):
2113 make_decoder = codecs.getincrementaldecoder(self._encoding)
2114 decoder = make_decoder(self._errors)
2115 if self._readuniversal:
2116 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
2117 self._decoder = decoder
2118 return decoder
2119
2120 # The following three methods implement an ADT for _decoded_chars.
2121 # Text returned from the decoder is buffered here until the client
2122 # requests it by calling our read() or readline() method.
2123 def _set_decoded_chars(self, chars):
2124 """Set the _decoded_chars buffer."""
2125 self._decoded_chars = chars
2126 self._decoded_chars_used = 0
2127
2128 def _get_decoded_chars(self, n=None):
2129 """Advance into the _decoded_chars buffer."""
2130 offset = self._decoded_chars_used
2131 if n is None:
2132 chars = self._decoded_chars[offset:]
2133 else:
2134 chars = self._decoded_chars[offset:offset + n]
2135 self._decoded_chars_used += len(chars)
2136 return chars
2137
2138 def _rewind_decoded_chars(self, n):
2139 """Rewind the _decoded_chars buffer."""
2140 if self._decoded_chars_used < n:
2141 raise AssertionError("rewind decoded_chars out of bounds")
2142 self._decoded_chars_used -= n
2143
2144 def _read_chunk(self):
2145 """
2146 Read and decode the next chunk of data from the BufferedReader.
2147 """
2148
2149 # The return value is True unless EOF was reached. The decoded
2150 # string is placed in self._decoded_chars (replacing its previous
2151 # value). The entire input chunk is sent to the decoder, though
2152 # some of it may remain buffered in the decoder, yet to be
2153 # converted.
2154
2155 if self._decoder is None:
2156 raise ValueError("no decoder")
2157
2158 if self._telling:
2159 # To prepare for tell(), we need to snapshot a point in the
2160 # file where the decoder's input buffer is empty.
2161
2162 dec_buffer, dec_flags = self._decoder.getstate()
2163 # Given this, we know there was a valid snapshot point
2164 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
2165
2166 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02002167 if self._has_read1:
2168 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
2169 else:
2170 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002171 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002172 decoded_chars = self._decoder.decode(input_chunk, eof)
2173 self._set_decoded_chars(decoded_chars)
2174 if decoded_chars:
2175 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
2176 else:
2177 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002178
2179 if self._telling:
2180 # At the snapshot point, len(dec_buffer) bytes before the read,
2181 # the next input to be decoded is dec_buffer + input_chunk.
2182 self._snapshot = (dec_flags, dec_buffer + input_chunk)
2183
2184 return not eof
2185
2186 def _pack_cookie(self, position, dec_flags=0,
2187 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
2188 # The meaning of a tell() cookie is: seek to position, set the
2189 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
2190 # into the decoder with need_eof as the EOF flag, then skip
2191 # chars_to_skip characters of the decoded result. For most simple
2192 # decoders, tell() will often just give a byte offset in the file.
2193 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
2194 (chars_to_skip<<192) | bool(need_eof)<<256)
2195
2196 def _unpack_cookie(self, bigint):
2197 rest, position = divmod(bigint, 1<<64)
2198 rest, dec_flags = divmod(rest, 1<<64)
2199 rest, bytes_to_feed = divmod(rest, 1<<64)
2200 need_eof, chars_to_skip = divmod(rest, 1<<64)
2201 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
2202
2203 def tell(self):
2204 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002205 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002206 if not self._telling:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002207 raise OSError("telling position disabled by next() call")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002208 self.flush()
2209 position = self.buffer.tell()
2210 decoder = self._decoder
2211 if decoder is None or self._snapshot is None:
2212 if self._decoded_chars:
2213 # This should never happen.
2214 raise AssertionError("pending decoded text")
2215 return position
2216
2217 # Skip backward to the snapshot point (see _read_chunk).
2218 dec_flags, next_input = self._snapshot
2219 position -= len(next_input)
2220
2221 # How many decoded characters have been used up since the snapshot?
2222 chars_to_skip = self._decoded_chars_used
2223 if chars_to_skip == 0:
2224 # We haven't moved from the snapshot point.
2225 return self._pack_cookie(position, dec_flags)
2226
2227 # Starting from the snapshot position, we will walk the decoder
2228 # forward until it gives us enough decoded characters.
2229 saved_state = decoder.getstate()
2230 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002231 # Fast search for an acceptable start point, close to our
2232 # current pos.
2233 # Rationale: calling decoder.decode() has a large overhead
2234 # regardless of chunk size; we want the number of such calls to
2235 # be O(1) in most situations (common decoders, non-crazy input).
2236 # Actually, it will be exactly 1 for fixed-size codecs (all
2237 # 8-bit codecs, also UTF-16 and UTF-32).
2238 skip_bytes = int(self._b2cratio * chars_to_skip)
2239 skip_back = 1
2240 assert skip_bytes <= len(next_input)
2241 while skip_bytes > 0:
2242 decoder.setstate((b'', dec_flags))
2243 # Decode up to temptative start point
2244 n = len(decoder.decode(next_input[:skip_bytes]))
2245 if n <= chars_to_skip:
2246 b, d = decoder.getstate()
2247 if not b:
2248 # Before pos and no bytes buffered in decoder => OK
2249 dec_flags = d
2250 chars_to_skip -= n
2251 break
2252 # Skip back by buffered amount and reset heuristic
2253 skip_bytes -= len(b)
2254 skip_back = 1
2255 else:
2256 # We're too far ahead, skip back a bit
2257 skip_bytes -= skip_back
2258 skip_back = skip_back * 2
2259 else:
2260 skip_bytes = 0
2261 decoder.setstate((b'', dec_flags))
2262
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002263 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002264 start_pos = position + skip_bytes
2265 start_flags = dec_flags
2266 if chars_to_skip == 0:
2267 # We haven't moved from the start point.
2268 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002269
2270 # Feed the decoder one byte at a time. As we go, note the
2271 # nearest "safe start point" before the current location
2272 # (a point where the decoder has nothing buffered, so seek()
2273 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002274 bytes_fed = 0
2275 need_eof = 0
2276 # Chars decoded since `start_pos`
2277 chars_decoded = 0
2278 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002279 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002280 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002281 dec_buffer, dec_flags = decoder.getstate()
2282 if not dec_buffer and chars_decoded <= chars_to_skip:
2283 # Decoder buffer is empty, so this is a safe start point.
2284 start_pos += bytes_fed
2285 chars_to_skip -= chars_decoded
2286 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
2287 if chars_decoded >= chars_to_skip:
2288 break
2289 else:
2290 # We didn't get enough decoded data; signal EOF to get more.
2291 chars_decoded += len(decoder.decode(b'', final=True))
2292 need_eof = 1
2293 if chars_decoded < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002294 raise OSError("can't reconstruct logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002295
2296 # The returned cookie corresponds to the last safe start point.
2297 return self._pack_cookie(
2298 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
2299 finally:
2300 decoder.setstate(saved_state)
2301
2302 def truncate(self, pos=None):
2303 self.flush()
2304 if pos is None:
2305 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00002306 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002307
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002308 def detach(self):
2309 if self.buffer is None:
2310 raise ValueError("buffer is already detached")
2311 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002312 buffer = self._buffer
2313 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002314 return buffer
2315
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002316 def seek(self, cookie, whence=0):
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002317 def _reset_encoder(position):
2318 """Reset the encoder (merely useful for proper BOM handling)"""
2319 try:
2320 encoder = self._encoder or self._get_encoder()
2321 except LookupError:
2322 # Sometimes the encoder doesn't exist
2323 pass
2324 else:
2325 if position != 0:
2326 encoder.setstate(0)
2327 else:
2328 encoder.reset()
2329
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002330 if self.closed:
2331 raise ValueError("tell on closed file")
2332 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002333 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002334 if whence == 1: # seek relative to current position
2335 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002336 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002337 # Seeking to the current position should attempt to
2338 # sync the underlying buffer with the current position.
2339 whence = 0
2340 cookie = self.tell()
2341 if whence == 2: # seek relative to end of file
2342 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002343 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002344 self.flush()
2345 position = self.buffer.seek(0, 2)
2346 self._set_decoded_chars('')
2347 self._snapshot = None
2348 if self._decoder:
2349 self._decoder.reset()
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002350 _reset_encoder(position)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002351 return position
2352 if whence != 0:
Jesus Cea94363612012-06-22 18:32:07 +02002353 raise ValueError("unsupported whence (%r)" % (whence,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002354 if cookie < 0:
2355 raise ValueError("negative seek position %r" % (cookie,))
2356 self.flush()
2357
2358 # The strategy of seek() is to go back to the safe start point
2359 # and replay the effect of read(chars_to_skip) from there.
2360 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
2361 self._unpack_cookie(cookie)
2362
2363 # Seek back to the safe start point.
2364 self.buffer.seek(start_pos)
2365 self._set_decoded_chars('')
2366 self._snapshot = None
2367
2368 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00002369 if cookie == 0 and self._decoder:
2370 self._decoder.reset()
2371 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002372 self._decoder = self._decoder or self._get_decoder()
2373 self._decoder.setstate((b'', dec_flags))
2374 self._snapshot = (dec_flags, b'')
2375
2376 if chars_to_skip:
2377 # Just like _read_chunk, feed the decoder and save a snapshot.
2378 input_chunk = self.buffer.read(bytes_to_feed)
2379 self._set_decoded_chars(
2380 self._decoder.decode(input_chunk, need_eof))
2381 self._snapshot = (dec_flags, input_chunk)
2382
2383 # Skip chars_to_skip of the decoded characters.
2384 if len(self._decoded_chars) < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002385 raise OSError("can't restore logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002386 self._decoded_chars_used = chars_to_skip
2387
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002388 _reset_encoder(cookie)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002389 return cookie
2390
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002391 def read(self, size=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00002392 self._checkReadable()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002393 if size is None:
2394 size = -1
Oren Milmande503602017-08-24 21:33:42 +03002395 else:
2396 try:
2397 size_index = size.__index__
2398 except AttributeError:
2399 raise TypeError(f"{size!r} is not an integer")
2400 else:
2401 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002402 decoder = self._decoder or self._get_decoder()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002403 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002404 # Read everything.
2405 result = (self._get_decoded_chars() +
2406 decoder.decode(self.buffer.read(), final=True))
2407 self._set_decoded_chars('')
2408 self._snapshot = None
2409 return result
2410 else:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002411 # Keep reading chunks until we have size characters to return.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002412 eof = False
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002413 result = self._get_decoded_chars(size)
2414 while len(result) < size and not eof:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002415 eof = not self._read_chunk()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002416 result += self._get_decoded_chars(size - len(result))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002417 return result
2418
2419 def __next__(self):
2420 self._telling = False
2421 line = self.readline()
2422 if not line:
2423 self._snapshot = None
2424 self._telling = self._seekable
2425 raise StopIteration
2426 return line
2427
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002428 def readline(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002429 if self.closed:
2430 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002431 if size is None:
2432 size = -1
Oren Milmande503602017-08-24 21:33:42 +03002433 else:
2434 try:
2435 size_index = size.__index__
2436 except AttributeError:
2437 raise TypeError(f"{size!r} is not an integer")
2438 else:
2439 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002440
2441 # Grab all the decoded text (we will rewind any extra bits later).
2442 line = self._get_decoded_chars()
2443
2444 start = 0
2445 # Make the decoder if it doesn't already exist.
2446 if not self._decoder:
2447 self._get_decoder()
2448
2449 pos = endpos = None
2450 while True:
2451 if self._readtranslate:
2452 # Newlines are already translated, only search for \n
2453 pos = line.find('\n', start)
2454 if pos >= 0:
2455 endpos = pos + 1
2456 break
2457 else:
2458 start = len(line)
2459
2460 elif self._readuniversal:
2461 # Universal newline search. Find any of \r, \r\n, \n
2462 # The decoder ensures that \r\n are not split in two pieces
2463
2464 # In C we'd look for these in parallel of course.
2465 nlpos = line.find("\n", start)
2466 crpos = line.find("\r", start)
2467 if crpos == -1:
2468 if nlpos == -1:
2469 # Nothing found
2470 start = len(line)
2471 else:
2472 # Found \n
2473 endpos = nlpos + 1
2474 break
2475 elif nlpos == -1:
2476 # Found lone \r
2477 endpos = crpos + 1
2478 break
2479 elif nlpos < crpos:
2480 # Found \n
2481 endpos = nlpos + 1
2482 break
2483 elif nlpos == crpos + 1:
2484 # Found \r\n
2485 endpos = crpos + 2
2486 break
2487 else:
2488 # Found \r
2489 endpos = crpos + 1
2490 break
2491 else:
2492 # non-universal
2493 pos = line.find(self._readnl)
2494 if pos >= 0:
2495 endpos = pos + len(self._readnl)
2496 break
2497
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002498 if size >= 0 and len(line) >= size:
2499 endpos = size # reached length size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002500 break
2501
2502 # No line ending seen yet - get more data'
2503 while self._read_chunk():
2504 if self._decoded_chars:
2505 break
2506 if self._decoded_chars:
2507 line += self._get_decoded_chars()
2508 else:
2509 # end of file
2510 self._set_decoded_chars('')
2511 self._snapshot = None
2512 return line
2513
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002514 if size >= 0 and endpos > size:
2515 endpos = size # don't exceed size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002516
2517 # Rewind _decoded_chars to just after the line ending we found.
2518 self._rewind_decoded_chars(len(line) - endpos)
2519 return line[:endpos]
2520
2521 @property
2522 def newlines(self):
2523 return self._decoder.newlines if self._decoder else None
2524
2525
2526class StringIO(TextIOWrapper):
2527 """Text I/O implementation using an in-memory buffer.
2528
2529 The initial_value argument sets the value of object. The newline
2530 argument is like the one of TextIOWrapper's constructor.
2531 """
2532
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002533 def __init__(self, initial_value="", newline="\n"):
2534 super(StringIO, self).__init__(BytesIO(),
2535 encoding="utf-8",
Serhiy Storchakac92ea762014-01-29 11:33:26 +02002536 errors="surrogatepass",
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002537 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002538 # Issue #5645: make universal newlines semantics the same as in the
2539 # C version, even under Windows.
2540 if newline is None:
2541 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002542 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002543 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002544 raise TypeError("initial_value must be str or None, not {0}"
2545 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002546 self.write(initial_value)
2547 self.seek(0)
2548
2549 def getvalue(self):
2550 self.flush()
Antoine Pitrou57839a62014-02-02 23:37:29 +01002551 decoder = self._decoder or self._get_decoder()
2552 old_state = decoder.getstate()
2553 decoder.reset()
2554 try:
2555 return decoder.decode(self.buffer.getvalue(), final=True)
2556 finally:
2557 decoder.setstate(old_state)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002558
2559 def __repr__(self):
2560 # TextIOWrapper tells the encoding in its repr. In StringIO,
Martin Panter7462b6492015-11-02 03:37:02 +00002561 # that's an implementation detail.
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002562 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002563
2564 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002565 def errors(self):
2566 return None
2567
2568 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002569 def encoding(self):
2570 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002571
2572 def detach(self):
2573 # This doesn't make sense on StringIO.
2574 self._unsupported("detach")
Neil Schemenauer0a1ff242017-09-22 10:17:30 -07002575
2576
2577# ____________________________________________________________
2578
2579import atexit, weakref
2580
2581_all_writers = weakref.WeakSet()
2582
2583def _register_writer(w):
2584 # keep weak-ref to buffered writer
2585 _all_writers.add(w)
2586
2587def _flush_all_writers():
2588 # Ensure all buffered writers are flushed before proceeding with
2589 # normal shutdown. Otherwise, if the underlying file objects get
2590 # finalized before the buffered writer wrapping it then any buffered
2591 # data will be lost.
2592 for w in _all_writers:
2593 try:
2594 w.flush()
2595 except:
2596 pass
2597atexit.register(_flush_all_writers)