blob: 1e105f27734c6b382710d559c10820fd0bdf40b0 [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()
1185
Martin Panter754aab22016-03-31 07:21:56 +00001186 def writable(self):
1187 return self.raw.writable()
1188
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001189 def write(self, b):
1190 if self.closed:
1191 raise ValueError("write to closed file")
1192 if isinstance(b, str):
1193 raise TypeError("can't write str to binary stream")
1194 with self._write_lock:
1195 # XXX we can implement some more tricks to try and avoid
1196 # partial writes
1197 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001198 # We're full, so let's pre-flush the buffer. (This may
1199 # raise BlockingIOError with characters_written == 0.)
1200 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001201 before = len(self._write_buf)
1202 self._write_buf.extend(b)
1203 written = len(self._write_buf) - before
1204 if len(self._write_buf) > self.buffer_size:
1205 try:
1206 self._flush_unlocked()
1207 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001208 if len(self._write_buf) > self.buffer_size:
1209 # We've hit the buffer_size. We have to accept a partial
1210 # write and cut back our buffer.
1211 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001212 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001213 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001214 raise BlockingIOError(e.errno, e.strerror, written)
1215 return written
1216
1217 def truncate(self, pos=None):
1218 with self._write_lock:
1219 self._flush_unlocked()
1220 if pos is None:
1221 pos = self.raw.tell()
1222 return self.raw.truncate(pos)
1223
1224 def flush(self):
1225 with self._write_lock:
1226 self._flush_unlocked()
1227
1228 def _flush_unlocked(self):
1229 if self.closed:
Jim Fasarakis-Hilliard1e73dbb2017-03-26 23:59:08 +03001230 raise ValueError("flush on closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001231 while self._write_buf:
1232 try:
1233 n = self.raw.write(self._write_buf)
1234 except BlockingIOError:
1235 raise RuntimeError("self.raw should implement RawIOBase: it "
1236 "should not raise BlockingIOError")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001237 if n is None:
1238 raise BlockingIOError(
1239 errno.EAGAIN,
1240 "write could not complete without blocking", 0)
1241 if n > len(self._write_buf) or n < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001242 raise OSError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001243 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001244
1245 def tell(self):
1246 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1247
1248 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001249 if whence not in valid_seek_flags:
1250 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001251 with self._write_lock:
1252 self._flush_unlocked()
1253 return _BufferedIOMixin.seek(self, pos, whence)
1254
1255
1256class BufferedRWPair(BufferedIOBase):
1257
1258 """A buffered reader and writer object together.
1259
1260 A buffered reader object and buffered writer object put together to
1261 form a sequential IO object that can read and write. This is typically
1262 used with a socket or two-way pipe.
1263
1264 reader and writer are RawIOBase objects that are readable and
1265 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001266 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001267 """
1268
1269 # XXX The usefulness of this (compared to having two separate IO
1270 # objects) is questionable.
1271
Florent Xicluna109d5732012-07-07 17:03:22 +02001272 def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001273 """Constructor.
1274
1275 The arguments are two RawIO instances.
1276 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001277 if not reader.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001278 raise OSError('"reader" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001279
1280 if not writer.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001281 raise OSError('"writer" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001282
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001283 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001284 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001285
Martin Panterccb2c0e2016-10-20 23:48:14 +00001286 def read(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001287 if size is None:
1288 size = -1
1289 return self.reader.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001290
1291 def readinto(self, b):
1292 return self.reader.readinto(b)
1293
1294 def write(self, b):
1295 return self.writer.write(b)
1296
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001297 def peek(self, size=0):
1298 return self.reader.peek(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001299
Martin Panterccb2c0e2016-10-20 23:48:14 +00001300 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001301 return self.reader.read1(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001302
Benjamin Petersona96fea02014-06-22 14:17:44 -07001303 def readinto1(self, b):
1304 return self.reader.readinto1(b)
1305
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001306 def readable(self):
1307 return self.reader.readable()
1308
1309 def writable(self):
1310 return self.writer.writable()
1311
1312 def flush(self):
1313 return self.writer.flush()
1314
1315 def close(self):
Serhiy Storchaka7665be62015-03-24 23:21:57 +02001316 try:
1317 self.writer.close()
1318 finally:
1319 self.reader.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001320
1321 def isatty(self):
1322 return self.reader.isatty() or self.writer.isatty()
1323
1324 @property
1325 def closed(self):
1326 return self.writer.closed
1327
1328
1329class BufferedRandom(BufferedWriter, BufferedReader):
1330
1331 """A buffered interface to random access streams.
1332
1333 The constructor creates a reader and writer for a seekable stream,
1334 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001335 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001336 """
1337
Florent Xicluna109d5732012-07-07 17:03:22 +02001338 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001339 raw._checkSeekable()
1340 BufferedReader.__init__(self, raw, buffer_size)
Florent Xicluna109d5732012-07-07 17:03:22 +02001341 BufferedWriter.__init__(self, raw, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001342
1343 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001344 if whence not in valid_seek_flags:
1345 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001346 self.flush()
1347 if self._read_buf:
1348 # Undo read ahead.
1349 with self._read_lock:
1350 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1351 # First do the raw seek, then empty the read buffer, so that
1352 # if the raw seek fails, we don't lose buffered data forever.
1353 pos = self.raw.seek(pos, whence)
1354 with self._read_lock:
1355 self._reset_read_buf()
1356 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001357 raise OSError("seek() returned invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001358 return pos
1359
1360 def tell(self):
1361 if self._write_buf:
1362 return BufferedWriter.tell(self)
1363 else:
1364 return BufferedReader.tell(self)
1365
1366 def truncate(self, pos=None):
1367 if pos is None:
1368 pos = self.tell()
1369 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001370 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001371
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001372 def read(self, size=None):
1373 if size is None:
1374 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001375 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001376 return BufferedReader.read(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001377
1378 def readinto(self, b):
1379 self.flush()
1380 return BufferedReader.readinto(self, b)
1381
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001382 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001383 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001384 return BufferedReader.peek(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001385
Martin Panterccb2c0e2016-10-20 23:48:14 +00001386 def read1(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001387 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001388 return BufferedReader.read1(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001389
Benjamin Petersona96fea02014-06-22 14:17:44 -07001390 def readinto1(self, b):
1391 self.flush()
1392 return BufferedReader.readinto1(self, b)
1393
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001394 def write(self, b):
1395 if self._read_buf:
1396 # Undo readahead
1397 with self._read_lock:
1398 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1399 self._reset_read_buf()
1400 return BufferedWriter.write(self, b)
1401
1402
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001403class FileIO(RawIOBase):
1404 _fd = -1
1405 _created = False
1406 _readable = False
1407 _writable = False
1408 _appending = False
1409 _seekable = None
1410 _closefd = True
1411
1412 def __init__(self, file, mode='r', closefd=True, opener=None):
1413 """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
1414 writing, exclusive creation or appending. The file will be created if it
1415 doesn't exist when opened for writing or appending; it will be truncated
1416 when opened for writing. A FileExistsError will be raised if it already
1417 exists when opened for creating. Opening a file for creating implies
1418 writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode
1419 to allow simultaneous reading and writing. A custom opener can be used by
1420 passing a callable as *opener*. The underlying file descriptor for the file
1421 object is then obtained by calling opener with (*name*, *flags*).
1422 *opener* must return an open file descriptor (passing os.open as *opener*
1423 results in functionality similar to passing None).
1424 """
1425 if self._fd >= 0:
1426 # Have to close the existing file first.
1427 try:
1428 if self._closefd:
1429 os.close(self._fd)
1430 finally:
1431 self._fd = -1
1432
1433 if isinstance(file, float):
1434 raise TypeError('integer argument expected, got float')
1435 if isinstance(file, int):
1436 fd = file
1437 if fd < 0:
1438 raise ValueError('negative file descriptor')
1439 else:
1440 fd = -1
1441
1442 if not isinstance(mode, str):
1443 raise TypeError('invalid mode: %s' % (mode,))
1444 if not set(mode) <= set('xrwab+'):
1445 raise ValueError('invalid mode: %s' % (mode,))
1446 if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1:
1447 raise ValueError('Must have exactly one of create/read/write/append '
1448 'mode and at most one plus')
1449
1450 if 'x' in mode:
1451 self._created = True
1452 self._writable = True
1453 flags = os.O_EXCL | os.O_CREAT
1454 elif 'r' in mode:
1455 self._readable = True
1456 flags = 0
1457 elif 'w' in mode:
1458 self._writable = True
1459 flags = os.O_CREAT | os.O_TRUNC
1460 elif 'a' in mode:
1461 self._writable = True
1462 self._appending = True
1463 flags = os.O_APPEND | os.O_CREAT
1464
1465 if '+' in mode:
1466 self._readable = True
1467 self._writable = True
1468
1469 if self._readable and self._writable:
1470 flags |= os.O_RDWR
1471 elif self._readable:
1472 flags |= os.O_RDONLY
1473 else:
1474 flags |= os.O_WRONLY
1475
1476 flags |= getattr(os, 'O_BINARY', 0)
1477
1478 noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or
1479 getattr(os, 'O_CLOEXEC', 0))
1480 flags |= noinherit_flag
1481
1482 owned_fd = None
1483 try:
1484 if fd < 0:
1485 if not closefd:
1486 raise ValueError('Cannot use closefd=False with file name')
1487 if opener is None:
1488 fd = os.open(file, flags, 0o666)
1489 else:
1490 fd = opener(file, flags)
1491 if not isinstance(fd, int):
1492 raise TypeError('expected integer from opener')
1493 if fd < 0:
1494 raise OSError('Negative file descriptor')
1495 owned_fd = fd
1496 if not noinherit_flag:
1497 os.set_inheritable(fd, False)
1498
1499 self._closefd = closefd
1500 fdfstat = os.fstat(fd)
1501 try:
1502 if stat.S_ISDIR(fdfstat.st_mode):
1503 raise IsADirectoryError(errno.EISDIR,
1504 os.strerror(errno.EISDIR), file)
1505 except AttributeError:
1506 # Ignore the AttribueError if stat.S_ISDIR or errno.EISDIR
1507 # don't exist.
1508 pass
1509 self._blksize = getattr(fdfstat, 'st_blksize', 0)
1510 if self._blksize <= 1:
1511 self._blksize = DEFAULT_BUFFER_SIZE
1512
1513 if _setmode:
1514 # don't translate newlines (\r\n <=> \n)
1515 _setmode(fd, os.O_BINARY)
1516
1517 self.name = file
1518 if self._appending:
1519 # For consistent behaviour, we explicitly seek to the
1520 # end of file (otherwise, it might be done only on the
1521 # first write()).
1522 os.lseek(fd, 0, SEEK_END)
1523 except:
1524 if owned_fd is not None:
1525 os.close(owned_fd)
1526 raise
1527 self._fd = fd
1528
1529 def __del__(self):
1530 if self._fd >= 0 and self._closefd and not self.closed:
1531 import warnings
1532 warnings.warn('unclosed file %r' % (self,), ResourceWarning,
Victor Stinnere19558a2016-03-23 00:28:08 +01001533 stacklevel=2, source=self)
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001534 self.close()
1535
1536 def __getstate__(self):
1537 raise TypeError("cannot serialize '%s' object", self.__class__.__name__)
1538
1539 def __repr__(self):
1540 class_name = '%s.%s' % (self.__class__.__module__,
1541 self.__class__.__qualname__)
1542 if self.closed:
1543 return '<%s [closed]>' % class_name
1544 try:
1545 name = self.name
1546 except AttributeError:
1547 return ('<%s fd=%d mode=%r closefd=%r>' %
1548 (class_name, self._fd, self.mode, self._closefd))
1549 else:
1550 return ('<%s name=%r mode=%r closefd=%r>' %
1551 (class_name, name, self.mode, self._closefd))
1552
1553 def _checkReadable(self):
1554 if not self._readable:
1555 raise UnsupportedOperation('File not open for reading')
1556
1557 def _checkWritable(self, msg=None):
1558 if not self._writable:
1559 raise UnsupportedOperation('File not open for writing')
1560
1561 def read(self, size=None):
1562 """Read at most size bytes, returned as bytes.
1563
1564 Only makes one system call, so less data may be returned than requested
1565 In non-blocking mode, returns None if no data is available.
1566 Return an empty bytes object at EOF.
1567 """
1568 self._checkClosed()
1569 self._checkReadable()
1570 if size is None or size < 0:
1571 return self.readall()
1572 try:
1573 return os.read(self._fd, size)
1574 except BlockingIOError:
1575 return None
1576
1577 def readall(self):
1578 """Read all data from the file, returned as bytes.
1579
1580 In non-blocking mode, returns as much as is immediately available,
1581 or None if no data is available. Return an empty bytes object at EOF.
1582 """
1583 self._checkClosed()
1584 self._checkReadable()
1585 bufsize = DEFAULT_BUFFER_SIZE
1586 try:
1587 pos = os.lseek(self._fd, 0, SEEK_CUR)
1588 end = os.fstat(self._fd).st_size
1589 if end >= pos:
1590 bufsize = end - pos + 1
1591 except OSError:
1592 pass
1593
1594 result = bytearray()
1595 while True:
1596 if len(result) >= bufsize:
1597 bufsize = len(result)
1598 bufsize += max(bufsize, DEFAULT_BUFFER_SIZE)
1599 n = bufsize - len(result)
1600 try:
1601 chunk = os.read(self._fd, n)
1602 except BlockingIOError:
1603 if result:
1604 break
1605 return None
1606 if not chunk: # reached the end of the file
1607 break
1608 result += chunk
1609
1610 return bytes(result)
1611
1612 def readinto(self, b):
1613 """Same as RawIOBase.readinto()."""
1614 m = memoryview(b).cast('B')
1615 data = self.read(len(m))
1616 n = len(data)
1617 m[:n] = data
1618 return n
1619
1620 def write(self, b):
1621 """Write bytes b to file, return number written.
1622
1623 Only makes one system call, so not all of the data may be written.
1624 The number of bytes actually written is returned. In non-blocking mode,
1625 returns None if the write would block.
1626 """
1627 self._checkClosed()
1628 self._checkWritable()
1629 try:
1630 return os.write(self._fd, b)
1631 except BlockingIOError:
1632 return None
1633
1634 def seek(self, pos, whence=SEEK_SET):
1635 """Move to new file position.
1636
1637 Argument offset is a byte count. Optional argument whence defaults to
1638 SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
1639 are SEEK_CUR or 1 (move relative to current position, positive or negative),
1640 and SEEK_END or 2 (move relative to end of file, usually negative, although
1641 many platforms allow seeking beyond the end of a file).
1642
1643 Note that not all file objects are seekable.
1644 """
1645 if isinstance(pos, float):
1646 raise TypeError('an integer is required')
1647 self._checkClosed()
1648 return os.lseek(self._fd, pos, whence)
1649
1650 def tell(self):
1651 """tell() -> int. Current file position.
1652
1653 Can raise OSError for non seekable files."""
1654 self._checkClosed()
1655 return os.lseek(self._fd, 0, SEEK_CUR)
1656
1657 def truncate(self, size=None):
1658 """Truncate the file to at most size bytes.
1659
1660 Size defaults to the current file position, as returned by tell().
1661 The current file position is changed to the value of size.
1662 """
1663 self._checkClosed()
1664 self._checkWritable()
1665 if size is None:
1666 size = self.tell()
1667 os.ftruncate(self._fd, size)
1668 return size
1669
1670 def close(self):
1671 """Close the file.
1672
1673 A closed file cannot be used for further I/O operations. close() may be
1674 called more than once without error.
1675 """
1676 if not self.closed:
1677 try:
1678 if self._closefd:
1679 os.close(self._fd)
1680 finally:
1681 super().close()
1682
1683 def seekable(self):
1684 """True if file supports random-access."""
1685 self._checkClosed()
1686 if self._seekable is None:
1687 try:
1688 self.tell()
1689 except OSError:
1690 self._seekable = False
1691 else:
1692 self._seekable = True
1693 return self._seekable
1694
1695 def readable(self):
1696 """True if file was opened in a read mode."""
1697 self._checkClosed()
1698 return self._readable
1699
1700 def writable(self):
1701 """True if file was opened in a write mode."""
1702 self._checkClosed()
1703 return self._writable
1704
1705 def fileno(self):
1706 """Return the underlying file descriptor (an integer)."""
1707 self._checkClosed()
1708 return self._fd
1709
1710 def isatty(self):
1711 """True if the file is connected to a TTY device."""
1712 self._checkClosed()
1713 return os.isatty(self._fd)
1714
1715 @property
1716 def closefd(self):
1717 """True if the file descriptor will be closed by close()."""
1718 return self._closefd
1719
1720 @property
1721 def mode(self):
1722 """String giving the file mode"""
1723 if self._created:
1724 if self._readable:
1725 return 'xb+'
1726 else:
1727 return 'xb'
1728 elif self._appending:
1729 if self._readable:
1730 return 'ab+'
1731 else:
1732 return 'ab'
1733 elif self._readable:
1734 if self._writable:
1735 return 'rb+'
1736 else:
1737 return 'rb'
1738 else:
1739 return 'wb'
1740
1741
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001742class TextIOBase(IOBase):
1743
1744 """Base class for text I/O.
1745
1746 This class provides a character and line based interface to stream
1747 I/O. There is no readinto method because Python's character strings
1748 are immutable. There is no public constructor.
1749 """
1750
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001751 def read(self, size=-1):
1752 """Read at most size characters from stream, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001753
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001754 Read from underlying buffer until we have size characters or we hit EOF.
1755 If size is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001756
1757 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001758 """
1759 self._unsupported("read")
1760
Raymond Hettinger3c940242011-01-12 23:39:31 +00001761 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001762 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001763 self._unsupported("write")
1764
Georg Brandl4d73b572011-01-13 07:13:06 +00001765 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001766 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001767 self._unsupported("truncate")
1768
Raymond Hettinger3c940242011-01-12 23:39:31 +00001769 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001770 """Read until newline or EOF.
1771
1772 Returns an empty string if EOF is hit immediately.
1773 """
1774 self._unsupported("readline")
1775
Raymond Hettinger3c940242011-01-12 23:39:31 +00001776 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001777 """
1778 Separate the underlying buffer from the TextIOBase and return it.
1779
1780 After the underlying buffer has been detached, the TextIO is in an
1781 unusable state.
1782 """
1783 self._unsupported("detach")
1784
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001785 @property
1786 def encoding(self):
1787 """Subclasses should override."""
1788 return None
1789
1790 @property
1791 def newlines(self):
1792 """Line endings translated so far.
1793
1794 Only line endings translated during reading are considered.
1795
1796 Subclasses should override.
1797 """
1798 return None
1799
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001800 @property
1801 def errors(self):
1802 """Error setting of the decoder or encoder.
1803
1804 Subclasses should override."""
1805 return None
1806
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001807io.TextIOBase.register(TextIOBase)
1808
1809
1810class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1811 r"""Codec used when reading a file in universal newlines mode. It wraps
1812 another incremental decoder, translating \r\n and \r into \n. It also
1813 records the types of newlines encountered. When used with
1814 translate=False, it ensures that the newline sequence is returned in
1815 one piece.
1816 """
1817 def __init__(self, decoder, translate, errors='strict'):
1818 codecs.IncrementalDecoder.__init__(self, errors=errors)
1819 self.translate = translate
1820 self.decoder = decoder
1821 self.seennl = 0
1822 self.pendingcr = False
1823
1824 def decode(self, input, final=False):
1825 # decode input (with the eventual \r from a previous pass)
1826 if self.decoder is None:
1827 output = input
1828 else:
1829 output = self.decoder.decode(input, final=final)
1830 if self.pendingcr and (output or final):
1831 output = "\r" + output
1832 self.pendingcr = False
1833
1834 # retain last \r even when not translating data:
1835 # then readline() is sure to get \r\n in one pass
1836 if output.endswith("\r") and not final:
1837 output = output[:-1]
1838 self.pendingcr = True
1839
1840 # Record which newlines are read
1841 crlf = output.count('\r\n')
1842 cr = output.count('\r') - crlf
1843 lf = output.count('\n') - crlf
1844 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1845 | (crlf and self._CRLF)
1846
1847 if self.translate:
1848 if crlf:
1849 output = output.replace("\r\n", "\n")
1850 if cr:
1851 output = output.replace("\r", "\n")
1852
1853 return output
1854
1855 def getstate(self):
1856 if self.decoder is None:
1857 buf = b""
1858 flag = 0
1859 else:
1860 buf, flag = self.decoder.getstate()
1861 flag <<= 1
1862 if self.pendingcr:
1863 flag |= 1
1864 return buf, flag
1865
1866 def setstate(self, state):
1867 buf, flag = state
1868 self.pendingcr = bool(flag & 1)
1869 if self.decoder is not None:
1870 self.decoder.setstate((buf, flag >> 1))
1871
1872 def reset(self):
1873 self.seennl = 0
1874 self.pendingcr = False
1875 if self.decoder is not None:
1876 self.decoder.reset()
1877
1878 _LF = 1
1879 _CR = 2
1880 _CRLF = 4
1881
1882 @property
1883 def newlines(self):
1884 return (None,
1885 "\n",
1886 "\r",
1887 ("\r", "\n"),
1888 "\r\n",
1889 ("\n", "\r\n"),
1890 ("\r", "\r\n"),
1891 ("\r", "\n", "\r\n")
1892 )[self.seennl]
1893
1894
1895class TextIOWrapper(TextIOBase):
1896
1897 r"""Character and line based layer over a BufferedIOBase object, buffer.
1898
1899 encoding gives the name of the encoding that the stream will be
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001900 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001901
1902 errors determines the strictness of encoding and decoding (see the
1903 codecs.register) and defaults to "strict".
1904
1905 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1906 handling of line endings. If it is None, universal newlines is
1907 enabled. With this enabled, on input, the lines endings '\n', '\r',
1908 or '\r\n' are translated to '\n' before being returned to the
1909 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001910 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001911 legal values, that newline becomes the newline when the file is read
1912 and it is returned untranslated. On output, '\n' is converted to the
1913 newline.
1914
1915 If line_buffering is True, a call to flush is implied when a call to
1916 write contains a newline character.
1917 """
1918
1919 _CHUNK_SIZE = 2048
1920
Andrew Svetlov4e9e9c12012-08-13 16:09:54 +03001921 # The write_through argument has no effect here since this
1922 # implementation always writes through. The argument is present only
1923 # so that the signature can match the signature of the C version.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001924 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001925 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001926 if newline is not None and not isinstance(newline, str):
1927 raise TypeError("illegal newline type: %r" % (type(newline),))
1928 if newline not in (None, "", "\n", "\r", "\r\n"):
1929 raise ValueError("illegal newline value: %r" % (newline,))
1930 if encoding is None:
1931 try:
1932 encoding = os.device_encoding(buffer.fileno())
1933 except (AttributeError, UnsupportedOperation):
1934 pass
1935 if encoding is None:
1936 try:
1937 import locale
Brett Cannoncd171c82013-07-04 17:43:24 -04001938 except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001939 # Importing locale may fail if Python is being built
1940 encoding = "ascii"
1941 else:
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001942 encoding = locale.getpreferredencoding(False)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001943
1944 if not isinstance(encoding, str):
1945 raise ValueError("invalid encoding: %r" % encoding)
1946
Nick Coghlana9b15242014-02-04 22:11:18 +10001947 if not codecs.lookup(encoding)._is_text_encoding:
1948 msg = ("%r is not a text encoding; "
1949 "use codecs.open() to handle arbitrary codecs")
1950 raise LookupError(msg % encoding)
1951
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001952 if errors is None:
1953 errors = "strict"
1954 else:
1955 if not isinstance(errors, str):
1956 raise ValueError("invalid errors: %r" % errors)
1957
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001958 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001959 self._encoding = encoding
1960 self._errors = errors
1961 self._readuniversal = not newline
1962 self._readtranslate = newline is None
1963 self._readnl = newline
1964 self._writetranslate = newline != ''
1965 self._writenl = newline or os.linesep
1966 self._encoder = None
1967 self._decoder = None
1968 self._decoded_chars = '' # buffer for text returned from decoder
1969 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1970 self._snapshot = None # info for reconstructing decoder state
1971 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001972 self._has_read1 = hasattr(self.buffer, 'read1')
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001973 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001974
Antoine Pitroue4501852009-05-14 18:55:55 +00001975 if self._seekable and self.writable():
1976 position = self.buffer.tell()
1977 if position != 0:
1978 try:
1979 self._get_encoder().setstate(0)
1980 except LookupError:
1981 # Sometimes the encoder doesn't exist
1982 pass
1983
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02001984 self._configure(line_buffering, write_through)
1985
1986 def _configure(self, line_buffering=False, write_through=False):
1987 self._line_buffering = line_buffering
1988 self._write_through = write_through
1989
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001990 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1991 # where dec_flags is the second (integer) item of the decoder state
1992 # and next_input is the chunk of input bytes that comes next after the
1993 # snapshot point. We use this to reconstruct decoder states in tell().
1994
1995 # Naming convention:
1996 # - "bytes_..." for integer variables that count input bytes
1997 # - "chars_..." for integer variables that count decoded characters
1998
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001999 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +03002000 result = "<{}.{}".format(self.__class__.__module__,
2001 self.__class__.__qualname__)
Antoine Pitrou716c4442009-05-23 19:04:03 +00002002 try:
2003 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -06002004 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002005 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00002006 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002007 result += " name={0!r}".format(name)
2008 try:
2009 mode = self.mode
Benjamin Peterson10e76b62014-12-21 20:51:50 -06002010 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002011 pass
2012 else:
2013 result += " mode={0!r}".format(mode)
2014 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00002015
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002016 @property
2017 def encoding(self):
2018 return self._encoding
2019
2020 @property
2021 def errors(self):
2022 return self._errors
2023
2024 @property
2025 def line_buffering(self):
2026 return self._line_buffering
2027
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002028 @property
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002029 def write_through(self):
2030 return self._write_through
2031
2032 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002033 def buffer(self):
2034 return self._buffer
2035
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002036 def reconfigure(self, *, line_buffering=None, write_through=None):
2037 """Reconfigure the text stream with new parameters.
2038
2039 This also flushes the stream.
2040 """
2041 if line_buffering is None:
2042 line_buffering = self.line_buffering
2043 if write_through is None:
2044 write_through = self.write_through
2045 self.flush()
2046 self._configure(line_buffering, write_through)
2047
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002048 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02002049 if self.closed:
2050 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002051 return self._seekable
2052
2053 def readable(self):
2054 return self.buffer.readable()
2055
2056 def writable(self):
2057 return self.buffer.writable()
2058
2059 def flush(self):
2060 self.buffer.flush()
2061 self._telling = self._seekable
2062
2063 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00002064 if self.buffer is not None and not self.closed:
Benjamin Peterson68623612012-12-20 11:53:11 -06002065 try:
2066 self.flush()
2067 finally:
2068 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002069
2070 @property
2071 def closed(self):
2072 return self.buffer.closed
2073
2074 @property
2075 def name(self):
2076 return self.buffer.name
2077
2078 def fileno(self):
2079 return self.buffer.fileno()
2080
2081 def isatty(self):
2082 return self.buffer.isatty()
2083
Raymond Hettinger00fa0392011-01-13 02:52:26 +00002084 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00002085 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002086 if self.closed:
2087 raise ValueError("write to closed file")
2088 if not isinstance(s, str):
2089 raise TypeError("can't write %s to text stream" %
2090 s.__class__.__name__)
2091 length = len(s)
2092 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
2093 if haslf and self._writetranslate and self._writenl != "\n":
2094 s = s.replace("\n", self._writenl)
2095 encoder = self._encoder or self._get_encoder()
2096 # XXX What if we were just reading?
2097 b = encoder.encode(s)
2098 self.buffer.write(b)
2099 if self._line_buffering and (haslf or "\r" in s):
2100 self.flush()
2101 self._snapshot = None
2102 if self._decoder:
2103 self._decoder.reset()
2104 return length
2105
2106 def _get_encoder(self):
2107 make_encoder = codecs.getincrementalencoder(self._encoding)
2108 self._encoder = make_encoder(self._errors)
2109 return self._encoder
2110
2111 def _get_decoder(self):
2112 make_decoder = codecs.getincrementaldecoder(self._encoding)
2113 decoder = make_decoder(self._errors)
2114 if self._readuniversal:
2115 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
2116 self._decoder = decoder
2117 return decoder
2118
2119 # The following three methods implement an ADT for _decoded_chars.
2120 # Text returned from the decoder is buffered here until the client
2121 # requests it by calling our read() or readline() method.
2122 def _set_decoded_chars(self, chars):
2123 """Set the _decoded_chars buffer."""
2124 self._decoded_chars = chars
2125 self._decoded_chars_used = 0
2126
2127 def _get_decoded_chars(self, n=None):
2128 """Advance into the _decoded_chars buffer."""
2129 offset = self._decoded_chars_used
2130 if n is None:
2131 chars = self._decoded_chars[offset:]
2132 else:
2133 chars = self._decoded_chars[offset:offset + n]
2134 self._decoded_chars_used += len(chars)
2135 return chars
2136
2137 def _rewind_decoded_chars(self, n):
2138 """Rewind the _decoded_chars buffer."""
2139 if self._decoded_chars_used < n:
2140 raise AssertionError("rewind decoded_chars out of bounds")
2141 self._decoded_chars_used -= n
2142
2143 def _read_chunk(self):
2144 """
2145 Read and decode the next chunk of data from the BufferedReader.
2146 """
2147
2148 # The return value is True unless EOF was reached. The decoded
2149 # string is placed in self._decoded_chars (replacing its previous
2150 # value). The entire input chunk is sent to the decoder, though
2151 # some of it may remain buffered in the decoder, yet to be
2152 # converted.
2153
2154 if self._decoder is None:
2155 raise ValueError("no decoder")
2156
2157 if self._telling:
2158 # To prepare for tell(), we need to snapshot a point in the
2159 # file where the decoder's input buffer is empty.
2160
2161 dec_buffer, dec_flags = self._decoder.getstate()
2162 # Given this, we know there was a valid snapshot point
2163 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
2164
2165 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02002166 if self._has_read1:
2167 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
2168 else:
2169 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002170 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002171 decoded_chars = self._decoder.decode(input_chunk, eof)
2172 self._set_decoded_chars(decoded_chars)
2173 if decoded_chars:
2174 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
2175 else:
2176 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002177
2178 if self._telling:
2179 # At the snapshot point, len(dec_buffer) bytes before the read,
2180 # the next input to be decoded is dec_buffer + input_chunk.
2181 self._snapshot = (dec_flags, dec_buffer + input_chunk)
2182
2183 return not eof
2184
2185 def _pack_cookie(self, position, dec_flags=0,
2186 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
2187 # The meaning of a tell() cookie is: seek to position, set the
2188 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
2189 # into the decoder with need_eof as the EOF flag, then skip
2190 # chars_to_skip characters of the decoded result. For most simple
2191 # decoders, tell() will often just give a byte offset in the file.
2192 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
2193 (chars_to_skip<<192) | bool(need_eof)<<256)
2194
2195 def _unpack_cookie(self, bigint):
2196 rest, position = divmod(bigint, 1<<64)
2197 rest, dec_flags = divmod(rest, 1<<64)
2198 rest, bytes_to_feed = divmod(rest, 1<<64)
2199 need_eof, chars_to_skip = divmod(rest, 1<<64)
2200 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
2201
2202 def tell(self):
2203 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002204 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002205 if not self._telling:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002206 raise OSError("telling position disabled by next() call")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002207 self.flush()
2208 position = self.buffer.tell()
2209 decoder = self._decoder
2210 if decoder is None or self._snapshot is None:
2211 if self._decoded_chars:
2212 # This should never happen.
2213 raise AssertionError("pending decoded text")
2214 return position
2215
2216 # Skip backward to the snapshot point (see _read_chunk).
2217 dec_flags, next_input = self._snapshot
2218 position -= len(next_input)
2219
2220 # How many decoded characters have been used up since the snapshot?
2221 chars_to_skip = self._decoded_chars_used
2222 if chars_to_skip == 0:
2223 # We haven't moved from the snapshot point.
2224 return self._pack_cookie(position, dec_flags)
2225
2226 # Starting from the snapshot position, we will walk the decoder
2227 # forward until it gives us enough decoded characters.
2228 saved_state = decoder.getstate()
2229 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002230 # Fast search for an acceptable start point, close to our
2231 # current pos.
2232 # Rationale: calling decoder.decode() has a large overhead
2233 # regardless of chunk size; we want the number of such calls to
2234 # be O(1) in most situations (common decoders, non-crazy input).
2235 # Actually, it will be exactly 1 for fixed-size codecs (all
2236 # 8-bit codecs, also UTF-16 and UTF-32).
2237 skip_bytes = int(self._b2cratio * chars_to_skip)
2238 skip_back = 1
2239 assert skip_bytes <= len(next_input)
2240 while skip_bytes > 0:
2241 decoder.setstate((b'', dec_flags))
2242 # Decode up to temptative start point
2243 n = len(decoder.decode(next_input[:skip_bytes]))
2244 if n <= chars_to_skip:
2245 b, d = decoder.getstate()
2246 if not b:
2247 # Before pos and no bytes buffered in decoder => OK
2248 dec_flags = d
2249 chars_to_skip -= n
2250 break
2251 # Skip back by buffered amount and reset heuristic
2252 skip_bytes -= len(b)
2253 skip_back = 1
2254 else:
2255 # We're too far ahead, skip back a bit
2256 skip_bytes -= skip_back
2257 skip_back = skip_back * 2
2258 else:
2259 skip_bytes = 0
2260 decoder.setstate((b'', dec_flags))
2261
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002262 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002263 start_pos = position + skip_bytes
2264 start_flags = dec_flags
2265 if chars_to_skip == 0:
2266 # We haven't moved from the start point.
2267 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002268
2269 # Feed the decoder one byte at a time. As we go, note the
2270 # nearest "safe start point" before the current location
2271 # (a point where the decoder has nothing buffered, so seek()
2272 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002273 bytes_fed = 0
2274 need_eof = 0
2275 # Chars decoded since `start_pos`
2276 chars_decoded = 0
2277 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002278 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002279 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002280 dec_buffer, dec_flags = decoder.getstate()
2281 if not dec_buffer and chars_decoded <= chars_to_skip:
2282 # Decoder buffer is empty, so this is a safe start point.
2283 start_pos += bytes_fed
2284 chars_to_skip -= chars_decoded
2285 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
2286 if chars_decoded >= chars_to_skip:
2287 break
2288 else:
2289 # We didn't get enough decoded data; signal EOF to get more.
2290 chars_decoded += len(decoder.decode(b'', final=True))
2291 need_eof = 1
2292 if chars_decoded < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002293 raise OSError("can't reconstruct logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002294
2295 # The returned cookie corresponds to the last safe start point.
2296 return self._pack_cookie(
2297 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
2298 finally:
2299 decoder.setstate(saved_state)
2300
2301 def truncate(self, pos=None):
2302 self.flush()
2303 if pos is None:
2304 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00002305 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002306
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002307 def detach(self):
2308 if self.buffer is None:
2309 raise ValueError("buffer is already detached")
2310 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002311 buffer = self._buffer
2312 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002313 return buffer
2314
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002315 def seek(self, cookie, whence=0):
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002316 def _reset_encoder(position):
2317 """Reset the encoder (merely useful for proper BOM handling)"""
2318 try:
2319 encoder = self._encoder or self._get_encoder()
2320 except LookupError:
2321 # Sometimes the encoder doesn't exist
2322 pass
2323 else:
2324 if position != 0:
2325 encoder.setstate(0)
2326 else:
2327 encoder.reset()
2328
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002329 if self.closed:
2330 raise ValueError("tell on closed file")
2331 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002332 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002333 if whence == 1: # seek relative to current position
2334 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002335 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002336 # Seeking to the current position should attempt to
2337 # sync the underlying buffer with the current position.
2338 whence = 0
2339 cookie = self.tell()
2340 if whence == 2: # seek relative to end of file
2341 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002342 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002343 self.flush()
2344 position = self.buffer.seek(0, 2)
2345 self._set_decoded_chars('')
2346 self._snapshot = None
2347 if self._decoder:
2348 self._decoder.reset()
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002349 _reset_encoder(position)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002350 return position
2351 if whence != 0:
Jesus Cea94363612012-06-22 18:32:07 +02002352 raise ValueError("unsupported whence (%r)" % (whence,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002353 if cookie < 0:
2354 raise ValueError("negative seek position %r" % (cookie,))
2355 self.flush()
2356
2357 # The strategy of seek() is to go back to the safe start point
2358 # and replay the effect of read(chars_to_skip) from there.
2359 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
2360 self._unpack_cookie(cookie)
2361
2362 # Seek back to the safe start point.
2363 self.buffer.seek(start_pos)
2364 self._set_decoded_chars('')
2365 self._snapshot = None
2366
2367 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00002368 if cookie == 0 and self._decoder:
2369 self._decoder.reset()
2370 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002371 self._decoder = self._decoder or self._get_decoder()
2372 self._decoder.setstate((b'', dec_flags))
2373 self._snapshot = (dec_flags, b'')
2374
2375 if chars_to_skip:
2376 # Just like _read_chunk, feed the decoder and save a snapshot.
2377 input_chunk = self.buffer.read(bytes_to_feed)
2378 self._set_decoded_chars(
2379 self._decoder.decode(input_chunk, need_eof))
2380 self._snapshot = (dec_flags, input_chunk)
2381
2382 # Skip chars_to_skip of the decoded characters.
2383 if len(self._decoded_chars) < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002384 raise OSError("can't restore logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002385 self._decoded_chars_used = chars_to_skip
2386
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002387 _reset_encoder(cookie)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002388 return cookie
2389
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002390 def read(self, size=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00002391 self._checkReadable()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002392 if size is None:
2393 size = -1
Oren Milmande503602017-08-24 21:33:42 +03002394 else:
2395 try:
2396 size_index = size.__index__
2397 except AttributeError:
2398 raise TypeError(f"{size!r} is not an integer")
2399 else:
2400 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002401 decoder = self._decoder or self._get_decoder()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002402 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002403 # Read everything.
2404 result = (self._get_decoded_chars() +
2405 decoder.decode(self.buffer.read(), final=True))
2406 self._set_decoded_chars('')
2407 self._snapshot = None
2408 return result
2409 else:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002410 # Keep reading chunks until we have size characters to return.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002411 eof = False
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002412 result = self._get_decoded_chars(size)
2413 while len(result) < size and not eof:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002414 eof = not self._read_chunk()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002415 result += self._get_decoded_chars(size - len(result))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002416 return result
2417
2418 def __next__(self):
2419 self._telling = False
2420 line = self.readline()
2421 if not line:
2422 self._snapshot = None
2423 self._telling = self._seekable
2424 raise StopIteration
2425 return line
2426
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002427 def readline(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002428 if self.closed:
2429 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002430 if size is None:
2431 size = -1
Oren Milmande503602017-08-24 21:33:42 +03002432 else:
2433 try:
2434 size_index = size.__index__
2435 except AttributeError:
2436 raise TypeError(f"{size!r} is not an integer")
2437 else:
2438 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002439
2440 # Grab all the decoded text (we will rewind any extra bits later).
2441 line = self._get_decoded_chars()
2442
2443 start = 0
2444 # Make the decoder if it doesn't already exist.
2445 if not self._decoder:
2446 self._get_decoder()
2447
2448 pos = endpos = None
2449 while True:
2450 if self._readtranslate:
2451 # Newlines are already translated, only search for \n
2452 pos = line.find('\n', start)
2453 if pos >= 0:
2454 endpos = pos + 1
2455 break
2456 else:
2457 start = len(line)
2458
2459 elif self._readuniversal:
2460 # Universal newline search. Find any of \r, \r\n, \n
2461 # The decoder ensures that \r\n are not split in two pieces
2462
2463 # In C we'd look for these in parallel of course.
2464 nlpos = line.find("\n", start)
2465 crpos = line.find("\r", start)
2466 if crpos == -1:
2467 if nlpos == -1:
2468 # Nothing found
2469 start = len(line)
2470 else:
2471 # Found \n
2472 endpos = nlpos + 1
2473 break
2474 elif nlpos == -1:
2475 # Found lone \r
2476 endpos = crpos + 1
2477 break
2478 elif nlpos < crpos:
2479 # Found \n
2480 endpos = nlpos + 1
2481 break
2482 elif nlpos == crpos + 1:
2483 # Found \r\n
2484 endpos = crpos + 2
2485 break
2486 else:
2487 # Found \r
2488 endpos = crpos + 1
2489 break
2490 else:
2491 # non-universal
2492 pos = line.find(self._readnl)
2493 if pos >= 0:
2494 endpos = pos + len(self._readnl)
2495 break
2496
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002497 if size >= 0 and len(line) >= size:
2498 endpos = size # reached length size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002499 break
2500
2501 # No line ending seen yet - get more data'
2502 while self._read_chunk():
2503 if self._decoded_chars:
2504 break
2505 if self._decoded_chars:
2506 line += self._get_decoded_chars()
2507 else:
2508 # end of file
2509 self._set_decoded_chars('')
2510 self._snapshot = None
2511 return line
2512
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002513 if size >= 0 and endpos > size:
2514 endpos = size # don't exceed size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002515
2516 # Rewind _decoded_chars to just after the line ending we found.
2517 self._rewind_decoded_chars(len(line) - endpos)
2518 return line[:endpos]
2519
2520 @property
2521 def newlines(self):
2522 return self._decoder.newlines if self._decoder else None
2523
2524
2525class StringIO(TextIOWrapper):
2526 """Text I/O implementation using an in-memory buffer.
2527
2528 The initial_value argument sets the value of object. The newline
2529 argument is like the one of TextIOWrapper's constructor.
2530 """
2531
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002532 def __init__(self, initial_value="", newline="\n"):
2533 super(StringIO, self).__init__(BytesIO(),
2534 encoding="utf-8",
Serhiy Storchakac92ea762014-01-29 11:33:26 +02002535 errors="surrogatepass",
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002536 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002537 # Issue #5645: make universal newlines semantics the same as in the
2538 # C version, even under Windows.
2539 if newline is None:
2540 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002541 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002542 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002543 raise TypeError("initial_value must be str or None, not {0}"
2544 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002545 self.write(initial_value)
2546 self.seek(0)
2547
2548 def getvalue(self):
2549 self.flush()
Antoine Pitrou57839a62014-02-02 23:37:29 +01002550 decoder = self._decoder or self._get_decoder()
2551 old_state = decoder.getstate()
2552 decoder.reset()
2553 try:
2554 return decoder.decode(self.buffer.getvalue(), final=True)
2555 finally:
2556 decoder.setstate(old_state)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002557
2558 def __repr__(self):
2559 # TextIOWrapper tells the encoding in its repr. In StringIO,
Martin Panter7462b6492015-11-02 03:37:02 +00002560 # that's an implementation detail.
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002561 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002562
2563 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002564 def errors(self):
2565 return None
2566
2567 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002568 def encoding(self):
2569 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002570
2571 def detach(self):
2572 # This doesn't make sense on StringIO.
2573 self._unsupported("detach")