blob: 43c24342ad6162ce97bc93a20fd105a3500c5f1e [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
Victor Stinnerbc2aa812019-05-23 03:45:09 +020036# Does io.IOBase finalizer log the exception if the close() method fails?
37# The exception is ignored silently by default in release build.
38_IOBASE_EMITS_UNRAISABLE = (hasattr(sys, "gettotalrefcount") or sys.flags.dev_mode)
39
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000040
Georg Brandl4d73b572011-01-13 07:13:06 +000041def open(file, mode="r", buffering=-1, encoding=None, errors=None,
Ross Lagerwall59142db2011-10-31 20:34:46 +020042 newline=None, closefd=True, opener=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000043
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020044 r"""Open file and return a stream. Raise OSError upon failure.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000045
46 file is either a text or byte string giving the name (and the path
47 if the file isn't in the current working directory) of the file to
48 be opened or an integer file descriptor of the file to be
49 wrapped. (If a file descriptor is given, it is closed when the
50 returned I/O object is closed, unless closefd is set to False.)
51
Charles-François Natalidc3044c2012-01-09 22:40:02 +010052 mode is an optional string that specifies the mode in which the file is
53 opened. It defaults to 'r' which means open for reading in text mode. Other
54 common values are 'w' for writing (truncating the file if it already
Charles-François Natalid612de12012-01-14 11:51:00 +010055 exists), 'x' for exclusive creation of a new file, and 'a' for appending
Charles-François Natalidc3044c2012-01-09 22:40:02 +010056 (which on some Unix systems, means that all writes append to the end of the
57 file regardless of the current seek position). In text mode, if encoding is
58 not specified the encoding used is platform dependent. (For reading and
59 writing raw bytes use binary mode and leave encoding unspecified.) The
60 available modes are:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000061
62 ========= ===============================================================
63 Character Meaning
64 --------- ---------------------------------------------------------------
65 'r' open for reading (default)
66 'w' open for writing, truncating the file first
Charles-François Natalidc3044c2012-01-09 22:40:02 +010067 'x' create a new file and open it for writing
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000068 'a' open for writing, appending to the end of the file if it exists
69 'b' binary mode
70 't' text mode (default)
71 '+' open a disk file for updating (reading and writing)
Serhiy Storchaka6787a382013-11-23 22:12:06 +020072 'U' universal newline mode (deprecated)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000073 ========= ===============================================================
74
75 The default mode is 'rt' (open for reading text). For binary random
76 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
Charles-François Natalidc3044c2012-01-09 22:40:02 +010077 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
78 raises an `FileExistsError` if the file already exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000079
80 Python distinguishes between files opened in binary and text modes,
81 even when the underlying operating system doesn't. Files opened in
82 binary mode (appending 'b' to the mode argument) return contents as
83 bytes objects without any decoding. In text mode (the default, or when
84 't' is appended to the mode argument), the contents of the file are
85 returned as strings, the bytes having been first decoded using a
86 platform-dependent encoding or using the specified encoding if given.
87
Serhiy Storchaka6787a382013-11-23 22:12:06 +020088 'U' mode is deprecated and will raise an exception in future versions
89 of Python. It has no effect in Python 3. Use newline to control
90 universal newlines mode.
91
Antoine Pitroud5587bc2009-12-19 21:08:31 +000092 buffering is an optional integer used to set the buffering policy.
93 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
94 line buffering (only usable in text mode), and an integer > 1 to indicate
95 the size of a fixed-size chunk buffer. When no buffering argument is
96 given, the default buffering policy works as follows:
97
98 * Binary files are buffered in fixed-size chunks; the size of the buffer
99 is chosen using a heuristic trying to determine the underlying device's
100 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
101 On many systems, the buffer will typically be 4096 or 8192 bytes long.
102
103 * "Interactive" text files (files for which isatty() returns True)
104 use line buffering. Other text files use the policy described above
105 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000106
Raymond Hettingercbb80892011-01-13 18:15:51 +0000107 encoding is the str name of the encoding used to decode or encode the
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000108 file. This should only be used in text mode. The default encoding is
109 platform dependent, but any encoding supported by Python can be
110 passed. See the codecs module for the list of supported encodings.
111
112 errors is an optional string that specifies how encoding errors are to
113 be handled---this argument should not be used in binary mode. Pass
114 'strict' to raise a ValueError exception if there is an encoding error
115 (the default of None has the same effect), or pass 'ignore' to ignore
116 errors. (Note that ignoring encoding errors can lead to data loss.)
117 See the documentation for codecs.register for a list of the permitted
118 encoding error strings.
119
Raymond Hettingercbb80892011-01-13 18:15:51 +0000120 newline is a string controlling how universal newlines works (it only
121 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
122 as follows:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000123
124 * On input, if newline is None, universal newlines mode is
125 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
126 these are translated into '\n' before being returned to the
127 caller. If it is '', universal newline mode is enabled, but line
128 endings are returned to the caller untranslated. If it has any of
129 the other legal values, input lines are only terminated by the given
130 string, and the line ending is returned to the caller untranslated.
131
132 * On output, if newline is None, any '\n' characters written are
133 translated to the system default line separator, os.linesep. If
134 newline is '', no translation takes place. If newline is any of the
135 other legal values, any '\n' characters written are translated to
136 the given string.
137
Raymond Hettingercbb80892011-01-13 18:15:51 +0000138 closedfd is a bool. If closefd is False, the underlying file descriptor will
139 be kept open when the file is closed. This does not work when a file name is
140 given and must be True in that case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000141
Victor Stinnerdaf45552013-08-28 00:53:59 +0200142 The newly created file is non-inheritable.
143
Ross Lagerwall59142db2011-10-31 20:34:46 +0200144 A custom opener can be used by passing a callable as *opener*. The
145 underlying file descriptor for the file object is then obtained by calling
146 *opener* with (*file*, *flags*). *opener* must return an open file
147 descriptor (passing os.open as *opener* results in functionality similar to
148 passing None).
149
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000150 open() returns a file object whose type depends on the mode, and
151 through which the standard file operations such as reading and writing
152 are performed. When open() is used to open a file in a text mode ('w',
153 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
154 a file in a binary mode, the returned class varies: in read binary
155 mode, it returns a BufferedReader; in write binary and append binary
156 modes, it returns a BufferedWriter, and in read/write mode, it returns
157 a BufferedRandom.
158
159 It is also possible to use a string or bytearray as a file for both
160 reading and writing. For strings StringIO can be used like a file
161 opened in a text mode, and for bytes a BytesIO can be used like a file
162 opened in a binary mode.
163 """
Ethan Furmand62548a2016-06-04 14:38:43 -0700164 if not isinstance(file, int):
165 file = os.fspath(file)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000166 if not isinstance(file, (str, bytes, int)):
167 raise TypeError("invalid file: %r" % file)
168 if not isinstance(mode, str):
169 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000170 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000171 raise TypeError("invalid buffering: %r" % buffering)
172 if encoding is not None and not isinstance(encoding, str):
173 raise TypeError("invalid encoding: %r" % encoding)
174 if errors is not None and not isinstance(errors, str):
175 raise TypeError("invalid errors: %r" % errors)
176 modes = set(mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100177 if modes - set("axrwb+tU") or len(mode) > len(modes):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000178 raise ValueError("invalid mode: %r" % mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100179 creating = "x" in modes
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000180 reading = "r" in modes
181 writing = "w" in modes
182 appending = "a" in modes
183 updating = "+" in modes
184 text = "t" in modes
185 binary = "b" in modes
186 if "U" in modes:
Robert Collinsc94a1dc2015-07-26 06:43:13 +1200187 if creating or writing or appending or updating:
188 raise ValueError("mode U cannot be combined with 'x', 'w', 'a', or '+'")
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200189 import warnings
190 warnings.warn("'U' mode is deprecated",
191 DeprecationWarning, 2)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000192 reading = True
193 if text and binary:
194 raise ValueError("can't have text and binary mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100195 if creating + reading + writing + appending > 1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000196 raise ValueError("can't have read/write/append mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100197 if not (creating or reading or writing or appending):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000198 raise ValueError("must have exactly one of read/write/append mode")
199 if binary and encoding is not None:
200 raise ValueError("binary mode doesn't take an encoding argument")
201 if binary and errors is not None:
202 raise ValueError("binary mode doesn't take an errors argument")
203 if binary and newline is not None:
204 raise ValueError("binary mode doesn't take a newline argument")
Alexey Izbysheva2670562018-10-20 03:22:31 +0300205 if binary and buffering == 1:
206 import warnings
207 warnings.warn("line buffering (buffering=1) isn't supported in binary "
208 "mode, the default buffer size will be used",
209 RuntimeWarning, 2)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000210 raw = FileIO(file,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100211 (creating and "x" or "") +
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000212 (reading and "r" or "") +
213 (writing and "w" or "") +
214 (appending and "a" or "") +
215 (updating and "+" or ""),
Ross Lagerwall59142db2011-10-31 20:34:46 +0200216 closefd, opener=opener)
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300217 result = raw
218 try:
219 line_buffering = False
220 if buffering == 1 or buffering < 0 and raw.isatty():
221 buffering = -1
222 line_buffering = True
223 if buffering < 0:
224 buffering = DEFAULT_BUFFER_SIZE
225 try:
226 bs = os.fstat(raw.fileno()).st_blksize
227 except (OSError, AttributeError):
228 pass
229 else:
230 if bs > 1:
231 buffering = bs
232 if buffering < 0:
233 raise ValueError("invalid buffering size")
234 if buffering == 0:
235 if binary:
236 return result
237 raise ValueError("can't have unbuffered text I/O")
238 if updating:
239 buffer = BufferedRandom(raw, buffering)
240 elif creating or writing or appending:
241 buffer = BufferedWriter(raw, buffering)
242 elif reading:
243 buffer = BufferedReader(raw, buffering)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000244 else:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300245 raise ValueError("unknown mode: %r" % mode)
246 result = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000247 if binary:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300248 return result
249 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
250 result = text
251 text.mode = mode
252 return result
253 except:
254 result.close()
255 raise
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000256
Steve Dowerb82e17e2019-05-23 08:45:22 -0700257# Define a default pure-Python implementation for open_code()
258# that does not allow hooks. Warn on first use. Defined for tests.
259def _open_code_with_warning(path):
260 """Opens the provided file with mode ``'rb'``. This function
261 should be used when the intent is to treat the contents as
262 executable code.
263
264 ``path`` should be an absolute path.
265
266 When supported by the runtime, this function can be hooked
267 in order to allow embedders more control over code files.
268 This functionality is not supported on the current runtime.
269 """
270 import warnings
271 warnings.warn("_pyio.open_code() may not be using hooks",
272 RuntimeWarning, 2)
273 return open(path, "rb")
274
275try:
276 open_code = io.open_code
277except AttributeError:
278 open_code = _open_code_with_warning
279
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000280
281class DocDescriptor:
282 """Helper for builtins.open.__doc__
283 """
284 def __get__(self, obj, typ):
285 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000286 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000287 "errors=None, newline=None, closefd=True)\n\n" +
288 open.__doc__)
289
290class OpenWrapper:
291 """Wrapper for builtins.open
292
293 Trick so that open won't become a bound method when stored
294 as a class variable (as dbm.dumb does).
295
Nick Coghland6009512014-11-20 21:39:37 +1000296 See initstdio() in Python/pylifecycle.c.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000297 """
298 __doc__ = DocDescriptor()
299
300 def __new__(cls, *args, **kwargs):
301 return open(*args, **kwargs)
302
303
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000304# In normal operation, both `UnsupportedOperation`s should be bound to the
305# same object.
306try:
307 UnsupportedOperation = io.UnsupportedOperation
308except AttributeError:
Serhiy Storchaka606ab862016-12-07 13:31:20 +0200309 class UnsupportedOperation(OSError, ValueError):
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000310 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000311
312
313class IOBase(metaclass=abc.ABCMeta):
314
315 """The abstract base class for all I/O classes, acting on streams of
316 bytes. There is no public constructor.
317
318 This class provides dummy implementations for many methods that
319 derived classes can override selectively; the default implementations
320 represent a file that cannot be read, written or seeked.
321
Steve Palmer7b97ab32019-04-09 05:35:27 +0100322 Even though IOBase does not declare read or write because
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000323 their signatures will vary, implementations and clients should
324 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000325 may raise UnsupportedOperation when operations they do not support are
326 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000327
328 The basic type used for binary data read from or written to a file is
Steve Palmer7b97ab32019-04-09 05:35:27 +0100329 bytes. Other bytes-like objects are accepted as method arguments too.
330 Text I/O classes work with str data.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000331
332 Note that calling any method (even inquiries) on a closed stream is
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200333 undefined. Implementations may raise OSError in this case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000334
335 IOBase (and its subclasses) support the iterator protocol, meaning
336 that an IOBase object can be iterated over yielding the lines in a
337 stream.
338
339 IOBase also supports the :keyword:`with` statement. In this example,
340 fp is closed after the suite of the with statement is complete:
341
342 with open('spam.txt', 'r') as fp:
343 fp.write('Spam and eggs!')
344 """
345
346 ### Internal ###
347
Raymond Hettinger3c940242011-01-12 23:39:31 +0000348 def _unsupported(self, name):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200349 """Internal: raise an OSError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000350 raise UnsupportedOperation("%s.%s() not supported" %
351 (self.__class__.__name__, name))
352
353 ### Positioning ###
354
Georg Brandl4d73b572011-01-13 07:13:06 +0000355 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000356 """Change stream position.
357
Terry Jan Reedyc30b7b12013-03-11 17:57:08 -0400358 Change the stream position to byte offset pos. Argument pos is
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000359 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000360 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000361
362 * 0 -- start of stream (the default); offset should be zero or positive
363 * 1 -- current stream position; offset may be negative
364 * 2 -- end of stream; offset is usually negative
Jesus Cea94363612012-06-22 18:32:07 +0200365 Some operating systems / file systems could provide additional values.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000366
Raymond Hettingercbb80892011-01-13 18:15:51 +0000367 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000368 """
369 self._unsupported("seek")
370
Raymond Hettinger3c940242011-01-12 23:39:31 +0000371 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000372 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000373 return self.seek(0, 1)
374
Georg Brandl4d73b572011-01-13 07:13:06 +0000375 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000376 """Truncate file to size bytes.
377
378 Size defaults to the current IO position as reported by tell(). Return
379 the new size.
380 """
381 self._unsupported("truncate")
382
383 ### Flush and close ###
384
Raymond Hettinger3c940242011-01-12 23:39:31 +0000385 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000386 """Flush write buffers, if applicable.
387
388 This is not implemented for read-only and non-blocking streams.
389 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000390 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000391 # XXX Should this return the number of bytes written???
392
393 __closed = False
394
Raymond Hettinger3c940242011-01-12 23:39:31 +0000395 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000396 """Flush and close the IO object.
397
398 This method has no effect if the file is already closed.
399 """
400 if not self.__closed:
Benjamin Peterson68623612012-12-20 11:53:11 -0600401 try:
402 self.flush()
403 finally:
404 self.__closed = True
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000405
Raymond Hettinger3c940242011-01-12 23:39:31 +0000406 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000407 """Destructor. Calls close()."""
Victor Stinnerbc2aa812019-05-23 03:45:09 +0200408 if _IOBASE_EMITS_UNRAISABLE:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000409 self.close()
Victor Stinnerbc2aa812019-05-23 03:45:09 +0200410 else:
411 # The try/except block is in case this is called at program
412 # exit time, when it's possible that globals have already been
413 # deleted, and then the close() call might fail. Since
414 # there's nothing we can do about such failures and they annoy
415 # the end users, we suppress the traceback.
416 try:
417 self.close()
418 except:
419 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000420
421 ### Inquiries ###
422
Raymond Hettinger3c940242011-01-12 23:39:31 +0000423 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000424 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000425
Martin Panter754aab22016-03-31 07:21:56 +0000426 If False, seek(), tell() and truncate() will raise OSError.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000427 This method may need to do a test seek().
428 """
429 return False
430
431 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000432 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000433 """
434 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000435 raise UnsupportedOperation("File or stream is not seekable."
436 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000437
Raymond Hettinger3c940242011-01-12 23:39:31 +0000438 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000439 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000440
Martin Panter754aab22016-03-31 07:21:56 +0000441 If False, read() will raise OSError.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000442 """
443 return False
444
445 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000446 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000447 """
448 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000449 raise UnsupportedOperation("File or stream is not readable."
450 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000451
Raymond Hettinger3c940242011-01-12 23:39:31 +0000452 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000453 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000454
Martin Panter754aab22016-03-31 07:21:56 +0000455 If False, write() and truncate() will raise OSError.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000456 """
457 return False
458
459 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000460 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000461 """
462 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000463 raise UnsupportedOperation("File or stream is not writable."
464 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000465
466 @property
467 def closed(self):
468 """closed: bool. True iff the file has been closed.
469
470 For backwards compatibility, this is a property, not a predicate.
471 """
472 return self.__closed
473
474 def _checkClosed(self, msg=None):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300475 """Internal: raise a ValueError if file is closed
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000476 """
477 if self.closed:
478 raise ValueError("I/O operation on closed file."
479 if msg is None else msg)
480
481 ### Context manager ###
482
Raymond Hettinger3c940242011-01-12 23:39:31 +0000483 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000484 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000485 self._checkClosed()
486 return self
487
Raymond Hettinger3c940242011-01-12 23:39:31 +0000488 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000489 """Context management protocol. Calls close()"""
490 self.close()
491
492 ### Lower-level APIs ###
493
494 # XXX Should these be present even if unimplemented?
495
Raymond Hettinger3c940242011-01-12 23:39:31 +0000496 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000497 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000498
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200499 An OSError is raised if the IO object does not use a file descriptor.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000500 """
501 self._unsupported("fileno")
502
Raymond Hettinger3c940242011-01-12 23:39:31 +0000503 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000504 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000505
506 Return False if it can't be determined.
507 """
508 self._checkClosed()
509 return False
510
511 ### Readline[s] and writelines ###
512
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300513 def readline(self, size=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000514 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000515
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300516 If size is specified, at most size bytes will be read.
517 Size should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000518
519 The line terminator is always b'\n' for binary files; for text
520 files, the newlines argument to open can be used to select the line
521 terminator(s) recognized.
522 """
523 # For backwards compatibility, a (slowish) readline().
524 if hasattr(self, "peek"):
525 def nreadahead():
526 readahead = self.peek(1)
527 if not readahead:
528 return 1
529 n = (readahead.find(b"\n") + 1) or len(readahead)
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300530 if size >= 0:
531 n = min(n, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000532 return n
533 else:
534 def nreadahead():
535 return 1
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300536 if size is None:
537 size = -1
Oren Milmande503602017-08-24 21:33:42 +0300538 else:
539 try:
540 size_index = size.__index__
541 except AttributeError:
542 raise TypeError(f"{size!r} is not an integer")
543 else:
544 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000545 res = bytearray()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300546 while size < 0 or len(res) < size:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000547 b = self.read(nreadahead())
548 if not b:
549 break
550 res += b
551 if res.endswith(b"\n"):
552 break
553 return bytes(res)
554
555 def __iter__(self):
556 self._checkClosed()
557 return self
558
559 def __next__(self):
560 line = self.readline()
561 if not line:
562 raise StopIteration
563 return line
564
565 def readlines(self, hint=None):
566 """Return a list of lines from the stream.
567
568 hint can be specified to control the number of lines read: no more
569 lines will be read if the total size (in bytes/characters) of all
570 lines so far exceeds hint.
571 """
572 if hint is None or hint <= 0:
573 return list(self)
574 n = 0
575 lines = []
576 for line in self:
577 lines.append(line)
578 n += len(line)
579 if n >= hint:
580 break
581 return lines
582
583 def writelines(self, lines):
Marcin Niemiraab865212019-04-22 21:13:51 +1000584 """Write a list of lines to the stream.
585
586 Line separators are not added, so it is usual for each of the lines
587 provided to have a line separator at the end.
588 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000589 self._checkClosed()
590 for line in lines:
591 self.write(line)
592
593io.IOBase.register(IOBase)
594
595
596class RawIOBase(IOBase):
597
598 """Base class for raw binary I/O."""
599
600 # The read() method is implemented by calling readinto(); derived
601 # classes that want to support read() only need to implement
602 # readinto() as a primitive operation. In general, readinto() can be
603 # more efficient than read().
604
605 # (It would be tempting to also provide an implementation of
606 # readinto() in terms of read(), in case the latter is a more suitable
607 # primitive operation, but that would lead to nasty recursion in case
608 # a subclass doesn't implement either.)
609
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300610 def read(self, size=-1):
611 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000612
613 Returns an empty bytes object on EOF, or None if the object is
614 set not to block and has no data to read.
615 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300616 if size is None:
617 size = -1
618 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000619 return self.readall()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300620 b = bytearray(size.__index__())
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000621 n = self.readinto(b)
Antoine Pitrou328ec742010-09-14 18:37:24 +0000622 if n is None:
623 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000624 del b[n:]
625 return bytes(b)
626
627 def readall(self):
628 """Read until EOF, using multiple read() call."""
629 res = bytearray()
630 while True:
631 data = self.read(DEFAULT_BUFFER_SIZE)
632 if not data:
633 break
634 res += data
Victor Stinnera80987f2011-05-25 22:47:16 +0200635 if res:
636 return bytes(res)
637 else:
638 # b'' or None
639 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000640
Raymond Hettinger3c940242011-01-12 23:39:31 +0000641 def readinto(self, b):
Martin Panter6bb91f32016-05-28 00:41:57 +0000642 """Read bytes into a pre-allocated bytes-like object b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000643
Raymond Hettingercbb80892011-01-13 18:15:51 +0000644 Returns an int representing the number of bytes read (0 for EOF), or
645 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000646 """
647 self._unsupported("readinto")
648
Raymond Hettinger3c940242011-01-12 23:39:31 +0000649 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000650 """Write the given buffer to the IO stream.
651
Martin Panter6bb91f32016-05-28 00:41:57 +0000652 Returns the number of bytes written, which may be less than the
653 length of b in bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000654 """
655 self._unsupported("write")
656
657io.RawIOBase.register(RawIOBase)
658from _io import FileIO
659RawIOBase.register(FileIO)
660
661
662class BufferedIOBase(IOBase):
663
664 """Base class for buffered IO objects.
665
666 The main difference with RawIOBase is that the read() method
667 supports omitting the size argument, and does not have a default
668 implementation that defers to readinto().
669
670 In addition, read(), readinto() and write() may raise
671 BlockingIOError if the underlying raw stream is in non-blocking
672 mode and not ready; unlike their raw counterparts, they will never
673 return None.
674
675 A typical implementation should not inherit from a RawIOBase
676 implementation, but wrap one.
677 """
678
Martin Panterccb2c0e2016-10-20 23:48:14 +0000679 def read(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300680 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000681
682 If the argument is omitted, None, or negative, reads and
683 returns all data until EOF.
684
685 If the argument is positive, and the underlying raw stream is
686 not 'interactive', multiple raw reads may be issued to satisfy
687 the byte count (unless EOF is reached first). But for
688 interactive raw streams (XXX and for pipes?), at most one raw
689 read will be issued, and a short result does not imply that
690 EOF is imminent.
691
692 Returns an empty bytes array on EOF.
693
694 Raises BlockingIOError if the underlying raw stream has no
695 data at the moment.
696 """
697 self._unsupported("read")
698
Martin Panterccb2c0e2016-10-20 23:48:14 +0000699 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300700 """Read up to size bytes with at most one read() system call,
701 where size is an int.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000702 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000703 self._unsupported("read1")
704
Raymond Hettinger3c940242011-01-12 23:39:31 +0000705 def readinto(self, b):
Martin Panter6bb91f32016-05-28 00:41:57 +0000706 """Read bytes into a pre-allocated bytes-like object b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000707
708 Like read(), this may issue multiple reads to the underlying raw
709 stream, unless the latter is 'interactive'.
710
Raymond Hettingercbb80892011-01-13 18:15:51 +0000711 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000712
713 Raises BlockingIOError if the underlying raw stream has no
714 data at the moment.
715 """
Benjamin Petersona96fea02014-06-22 14:17:44 -0700716
717 return self._readinto(b, read1=False)
718
719 def readinto1(self, b):
Martin Panter6bb91f32016-05-28 00:41:57 +0000720 """Read bytes into buffer *b*, using at most one system call
Benjamin Petersona96fea02014-06-22 14:17:44 -0700721
722 Returns an int representing the number of bytes read (0 for EOF).
723
724 Raises BlockingIOError if the underlying raw stream has no
725 data at the moment.
726 """
727
728 return self._readinto(b, read1=True)
729
730 def _readinto(self, b, read1):
731 if not isinstance(b, memoryview):
732 b = memoryview(b)
733 b = b.cast('B')
734
735 if read1:
736 data = self.read1(len(b))
737 else:
738 data = self.read(len(b))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000739 n = len(data)
Benjamin Petersona96fea02014-06-22 14:17:44 -0700740
741 b[:n] = data
742
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000743 return n
744
Raymond Hettinger3c940242011-01-12 23:39:31 +0000745 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000746 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000747
Martin Panter6bb91f32016-05-28 00:41:57 +0000748 Return the number of bytes written, which is always the length of b
749 in bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000750
751 Raises BlockingIOError if the buffer is full and the
752 underlying raw stream cannot accept more data at the moment.
753 """
754 self._unsupported("write")
755
Raymond Hettinger3c940242011-01-12 23:39:31 +0000756 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000757 """
758 Separate the underlying raw stream from the buffer and return it.
759
760 After the raw stream has been detached, the buffer is in an unusable
761 state.
762 """
763 self._unsupported("detach")
764
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000765io.BufferedIOBase.register(BufferedIOBase)
766
767
768class _BufferedIOMixin(BufferedIOBase):
769
770 """A mixin implementation of BufferedIOBase with an underlying raw stream.
771
772 This passes most requests on to the underlying raw stream. It
773 does *not* provide implementations of read(), readinto() or
774 write().
775 """
776
777 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000778 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000779
780 ### Positioning ###
781
782 def seek(self, pos, whence=0):
783 new_position = self.raw.seek(pos, whence)
784 if new_position < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200785 raise OSError("seek() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000786 return new_position
787
788 def tell(self):
789 pos = self.raw.tell()
790 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200791 raise OSError("tell() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000792 return pos
793
794 def truncate(self, pos=None):
795 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
796 # and a flush may be necessary to synch both views of the current
797 # file state.
798 self.flush()
799
800 if pos is None:
801 pos = self.tell()
802 # XXX: Should seek() be used, instead of passing the position
803 # XXX directly to truncate?
804 return self.raw.truncate(pos)
805
806 ### Flush and close ###
807
808 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000809 if self.closed:
Jim Fasarakis-Hilliard1e73dbb2017-03-26 23:59:08 +0300810 raise ValueError("flush on closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000811 self.raw.flush()
812
813 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000814 if self.raw is not None and not self.closed:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +0100815 try:
816 # may raise BlockingIOError or BrokenPipeError etc
817 self.flush()
818 finally:
819 self.raw.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000820
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000821 def detach(self):
822 if self.raw is None:
823 raise ValueError("raw stream already detached")
824 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000825 raw = self._raw
826 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000827 return raw
828
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000829 ### Inquiries ###
830
831 def seekable(self):
832 return self.raw.seekable()
833
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000834 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000835 def raw(self):
836 return self._raw
837
838 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000839 def closed(self):
840 return self.raw.closed
841
842 @property
843 def name(self):
844 return self.raw.name
845
846 @property
847 def mode(self):
848 return self.raw.mode
849
Antoine Pitrou243757e2010-11-05 21:15:39 +0000850 def __getstate__(self):
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +0200851 raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
Antoine Pitrou243757e2010-11-05 21:15:39 +0000852
Antoine Pitrou716c4442009-05-23 19:04:03 +0000853 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300854 modname = self.__class__.__module__
855 clsname = self.__class__.__qualname__
Antoine Pitrou716c4442009-05-23 19:04:03 +0000856 try:
857 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -0600858 except Exception:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300859 return "<{}.{}>".format(modname, clsname)
Antoine Pitrou716c4442009-05-23 19:04:03 +0000860 else:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300861 return "<{}.{} name={!r}>".format(modname, clsname, name)
Antoine Pitrou716c4442009-05-23 19:04:03 +0000862
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000863 ### Lower-level APIs ###
864
865 def fileno(self):
866 return self.raw.fileno()
867
868 def isatty(self):
869 return self.raw.isatty()
870
871
872class BytesIO(BufferedIOBase):
873
874 """Buffered I/O implementation using an in-memory bytes buffer."""
875
Victor Stinnera3568412019-05-28 01:44:21 +0200876 # Initialize _buffer as soon as possible since it's used by __del__()
877 # which calls close()
878 _buffer = None
879
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000880 def __init__(self, initial_bytes=None):
881 buf = bytearray()
882 if initial_bytes is not None:
883 buf += initial_bytes
884 self._buffer = buf
885 self._pos = 0
886
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000887 def __getstate__(self):
888 if self.closed:
889 raise ValueError("__getstate__ on closed file")
890 return self.__dict__.copy()
891
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000892 def getvalue(self):
893 """Return the bytes value (contents) of the buffer
894 """
895 if self.closed:
896 raise ValueError("getvalue on closed file")
897 return bytes(self._buffer)
898
Antoine Pitrou972ee132010-09-06 18:48:21 +0000899 def getbuffer(self):
900 """Return a readable and writable view of the buffer.
901 """
Serhiy Storchakac057c382015-02-03 02:00:18 +0200902 if self.closed:
903 raise ValueError("getbuffer on closed file")
Antoine Pitrou972ee132010-09-06 18:48:21 +0000904 return memoryview(self._buffer)
905
Serhiy Storchakac057c382015-02-03 02:00:18 +0200906 def close(self):
Victor Stinnera3568412019-05-28 01:44:21 +0200907 if self._buffer is not None:
908 self._buffer.clear()
Serhiy Storchakac057c382015-02-03 02:00:18 +0200909 super().close()
910
Martin Panterccb2c0e2016-10-20 23:48:14 +0000911 def read(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000912 if self.closed:
913 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300914 if size is None:
915 size = -1
Oren Milmande503602017-08-24 21:33:42 +0300916 else:
917 try:
918 size_index = size.__index__
919 except AttributeError:
920 raise TypeError(f"{size!r} is not an integer")
921 else:
922 size = size_index()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300923 if size < 0:
924 size = len(self._buffer)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000925 if len(self._buffer) <= self._pos:
926 return b""
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300927 newpos = min(len(self._buffer), self._pos + size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000928 b = self._buffer[self._pos : newpos]
929 self._pos = newpos
930 return bytes(b)
931
Martin Panterccb2c0e2016-10-20 23:48:14 +0000932 def read1(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000933 """This is the same as read.
934 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300935 return self.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000936
937 def write(self, b):
938 if self.closed:
939 raise ValueError("write to closed file")
940 if isinstance(b, str):
941 raise TypeError("can't write str to binary stream")
Martin Panter6bb91f32016-05-28 00:41:57 +0000942 with memoryview(b) as view:
943 n = view.nbytes # Size of any bytes-like object
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000944 if n == 0:
945 return 0
946 pos = self._pos
947 if pos > len(self._buffer):
948 # Inserts null bytes between the current end of the file
949 # and the new write position.
950 padding = b'\x00' * (pos - len(self._buffer))
951 self._buffer += padding
952 self._buffer[pos:pos + n] = b
953 self._pos += n
954 return n
955
956 def seek(self, pos, whence=0):
957 if self.closed:
958 raise ValueError("seek on closed file")
959 try:
Oren Milmande503602017-08-24 21:33:42 +0300960 pos_index = pos.__index__
961 except AttributeError:
962 raise TypeError(f"{pos!r} is not an integer")
963 else:
964 pos = pos_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000965 if whence == 0:
966 if pos < 0:
967 raise ValueError("negative seek position %r" % (pos,))
968 self._pos = pos
969 elif whence == 1:
970 self._pos = max(0, self._pos + pos)
971 elif whence == 2:
972 self._pos = max(0, len(self._buffer) + pos)
973 else:
Jesus Cea94363612012-06-22 18:32:07 +0200974 raise ValueError("unsupported whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000975 return self._pos
976
977 def tell(self):
978 if self.closed:
979 raise ValueError("tell on closed file")
980 return self._pos
981
982 def truncate(self, pos=None):
983 if self.closed:
984 raise ValueError("truncate on closed file")
985 if pos is None:
986 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000987 else:
988 try:
Oren Milmande503602017-08-24 21:33:42 +0300989 pos_index = pos.__index__
990 except AttributeError:
991 raise TypeError(f"{pos!r} is not an integer")
992 else:
993 pos = pos_index()
Florent Xiclunab14930c2010-03-13 15:26:44 +0000994 if pos < 0:
995 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000996 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000997 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000998
999 def readable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02001000 if self.closed:
1001 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001002 return True
1003
1004 def writable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02001005 if self.closed:
1006 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001007 return True
1008
1009 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02001010 if self.closed:
1011 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001012 return True
1013
1014
1015class BufferedReader(_BufferedIOMixin):
1016
1017 """BufferedReader(raw[, buffer_size])
1018
1019 A buffer for a readable, sequential BaseRawIO object.
1020
1021 The constructor creates a BufferedReader for the given readable raw
1022 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
1023 is used.
1024 """
1025
1026 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
1027 """Create a new buffered reader using the given readable raw IO object.
1028 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001029 if not raw.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001030 raise OSError('"raw" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001031
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001032 _BufferedIOMixin.__init__(self, raw)
1033 if buffer_size <= 0:
1034 raise ValueError("invalid buffer size")
1035 self.buffer_size = buffer_size
1036 self._reset_read_buf()
1037 self._read_lock = Lock()
1038
Martin Panter754aab22016-03-31 07:21:56 +00001039 def readable(self):
1040 return self.raw.readable()
1041
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001042 def _reset_read_buf(self):
1043 self._read_buf = b""
1044 self._read_pos = 0
1045
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001046 def read(self, size=None):
1047 """Read size bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001048
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001049 Returns exactly size bytes of data unless the underlying raw IO
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001050 stream reaches EOF or if the call would block in non-blocking
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001051 mode. If size is negative, read until EOF or until read() would
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001052 block.
1053 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001054 if size is not None and size < -1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001055 raise ValueError("invalid number of bytes to read")
1056 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001057 return self._read_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001058
1059 def _read_unlocked(self, n=None):
1060 nodata_val = b""
1061 empty_values = (b"", None)
1062 buf = self._read_buf
1063 pos = self._read_pos
1064
1065 # Special case for when the number of bytes to read is unspecified.
1066 if n is None or n == -1:
1067 self._reset_read_buf()
Victor Stinnerb57f1082011-05-26 00:19:38 +02001068 if hasattr(self.raw, 'readall'):
1069 chunk = self.raw.readall()
1070 if chunk is None:
1071 return buf[pos:] or None
1072 else:
1073 return buf[pos:] + chunk
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001074 chunks = [buf[pos:]] # Strip the consumed bytes.
1075 current_size = 0
1076 while True:
1077 # Read until EOF or until read() would block.
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001078 chunk = self.raw.read()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001079 if chunk in empty_values:
1080 nodata_val = chunk
1081 break
1082 current_size += len(chunk)
1083 chunks.append(chunk)
1084 return b"".join(chunks) or nodata_val
1085
1086 # The number of bytes to read is specified, return at most n bytes.
1087 avail = len(buf) - pos # Length of the available buffered data.
1088 if n <= avail:
1089 # Fast path: the data to read is fully buffered.
1090 self._read_pos += n
1091 return buf[pos:pos+n]
1092 # Slow path: read from the stream until enough bytes are read,
1093 # or until an EOF occurs or until read() would block.
1094 chunks = [buf[pos:]]
1095 wanted = max(self.buffer_size, n)
1096 while avail < n:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001097 chunk = self.raw.read(wanted)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001098 if chunk in empty_values:
1099 nodata_val = chunk
1100 break
1101 avail += len(chunk)
1102 chunks.append(chunk)
Martin Pantere26da7c2016-06-02 10:07:09 +00001103 # n is more than avail only when an EOF occurred or when
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001104 # read() would have blocked.
1105 n = min(n, avail)
1106 out = b"".join(chunks)
1107 self._read_buf = out[n:] # Save the extra data in the buffer.
1108 self._read_pos = 0
1109 return out[:n] if out else nodata_val
1110
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001111 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001112 """Returns buffered bytes without advancing the position.
1113
1114 The argument indicates a desired minimal number of bytes; we
1115 do at most one raw read to satisfy it. We never return more
1116 than self.buffer_size.
1117 """
1118 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001119 return self._peek_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001120
1121 def _peek_unlocked(self, n=0):
1122 want = min(n, self.buffer_size)
1123 have = len(self._read_buf) - self._read_pos
1124 if have < want or have <= 0:
1125 to_read = self.buffer_size - have
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001126 current = self.raw.read(to_read)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001127 if current:
1128 self._read_buf = self._read_buf[self._read_pos:] + current
1129 self._read_pos = 0
1130 return self._read_buf[self._read_pos:]
1131
Martin Panterccb2c0e2016-10-20 23:48:14 +00001132 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001133 """Reads up to size bytes, with at most one read() system call."""
1134 # Returns up to size bytes. If at least one byte is buffered, we
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001135 # only return buffered bytes. Otherwise, we do one raw read.
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001136 if size < 0:
Martin Panterccb2c0e2016-10-20 23:48:14 +00001137 size = self.buffer_size
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001138 if size == 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001139 return b""
1140 with self._read_lock:
1141 self._peek_unlocked(1)
1142 return self._read_unlocked(
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001143 min(size, len(self._read_buf) - self._read_pos))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001144
Benjamin Petersona96fea02014-06-22 14:17:44 -07001145 # Implementing readinto() and readinto1() is not strictly necessary (we
1146 # could rely on the base class that provides an implementation in terms of
1147 # read() and read1()). We do it anyway to keep the _pyio implementation
1148 # similar to the io implementation (which implements the methods for
1149 # performance reasons).
1150 def _readinto(self, buf, read1):
1151 """Read data into *buf* with at most one system call."""
1152
Benjamin Petersona96fea02014-06-22 14:17:44 -07001153 # Need to create a memoryview object of type 'b', otherwise
1154 # we may not be able to assign bytes to it, and slicing it
1155 # would create a new object.
1156 if not isinstance(buf, memoryview):
1157 buf = memoryview(buf)
Martin Panter6bb91f32016-05-28 00:41:57 +00001158 if buf.nbytes == 0:
1159 return 0
Benjamin Petersona96fea02014-06-22 14:17:44 -07001160 buf = buf.cast('B')
1161
1162 written = 0
1163 with self._read_lock:
1164 while written < len(buf):
1165
1166 # First try to read from internal buffer
1167 avail = min(len(self._read_buf) - self._read_pos, len(buf))
1168 if avail:
1169 buf[written:written+avail] = \
1170 self._read_buf[self._read_pos:self._read_pos+avail]
1171 self._read_pos += avail
1172 written += avail
1173 if written == len(buf):
1174 break
1175
1176 # If remaining space in callers buffer is larger than
1177 # internal buffer, read directly into callers buffer
1178 if len(buf) - written > self.buffer_size:
1179 n = self.raw.readinto(buf[written:])
1180 if not n:
1181 break # eof
1182 written += n
1183
1184 # Otherwise refill internal buffer - unless we're
1185 # in read1 mode and already got some data
1186 elif not (read1 and written):
1187 if not self._peek_unlocked(1):
1188 break # eof
1189
1190 # In readinto1 mode, return as soon as we have some data
1191 if read1 and written:
1192 break
1193
1194 return written
1195
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001196 def tell(self):
1197 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1198
1199 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001200 if whence not in valid_seek_flags:
Jesus Cea990eff02012-04-26 17:05:31 +02001201 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001202 with self._read_lock:
1203 if whence == 1:
1204 pos -= len(self._read_buf) - self._read_pos
1205 pos = _BufferedIOMixin.seek(self, pos, whence)
1206 self._reset_read_buf()
1207 return pos
1208
1209class BufferedWriter(_BufferedIOMixin):
1210
1211 """A buffer for a writeable sequential RawIO object.
1212
1213 The constructor creates a BufferedWriter for the given writeable raw
1214 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001215 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001216 """
1217
Florent Xicluna109d5732012-07-07 17:03:22 +02001218 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001219 if not raw.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001220 raise OSError('"raw" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001221
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001222 _BufferedIOMixin.__init__(self, raw)
1223 if buffer_size <= 0:
1224 raise ValueError("invalid buffer size")
1225 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001226 self._write_buf = bytearray()
1227 self._write_lock = Lock()
1228
Martin Panter754aab22016-03-31 07:21:56 +00001229 def writable(self):
1230 return self.raw.writable()
1231
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001232 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001233 if isinstance(b, str):
1234 raise TypeError("can't write str to binary stream")
1235 with self._write_lock:
benfogle9703f092017-11-10 16:03:40 -05001236 if self.closed:
1237 raise ValueError("write to closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001238 # XXX we can implement some more tricks to try and avoid
1239 # partial writes
1240 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001241 # We're full, so let's pre-flush the buffer. (This may
1242 # raise BlockingIOError with characters_written == 0.)
1243 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001244 before = len(self._write_buf)
1245 self._write_buf.extend(b)
1246 written = len(self._write_buf) - before
1247 if len(self._write_buf) > self.buffer_size:
1248 try:
1249 self._flush_unlocked()
1250 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001251 if len(self._write_buf) > self.buffer_size:
1252 # We've hit the buffer_size. We have to accept a partial
1253 # write and cut back our buffer.
1254 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001255 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001256 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001257 raise BlockingIOError(e.errno, e.strerror, written)
1258 return written
1259
1260 def truncate(self, pos=None):
1261 with self._write_lock:
1262 self._flush_unlocked()
1263 if pos is None:
1264 pos = self.raw.tell()
1265 return self.raw.truncate(pos)
1266
1267 def flush(self):
1268 with self._write_lock:
1269 self._flush_unlocked()
1270
1271 def _flush_unlocked(self):
1272 if self.closed:
Jim Fasarakis-Hilliard1e73dbb2017-03-26 23:59:08 +03001273 raise ValueError("flush on closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001274 while self._write_buf:
1275 try:
1276 n = self.raw.write(self._write_buf)
1277 except BlockingIOError:
1278 raise RuntimeError("self.raw should implement RawIOBase: it "
1279 "should not raise BlockingIOError")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001280 if n is None:
1281 raise BlockingIOError(
1282 errno.EAGAIN,
1283 "write could not complete without blocking", 0)
1284 if n > len(self._write_buf) or n < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001285 raise OSError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001286 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001287
1288 def tell(self):
1289 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1290
1291 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001292 if whence not in valid_seek_flags:
1293 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001294 with self._write_lock:
1295 self._flush_unlocked()
1296 return _BufferedIOMixin.seek(self, pos, whence)
1297
benfogle9703f092017-11-10 16:03:40 -05001298 def close(self):
1299 with self._write_lock:
1300 if self.raw is None or self.closed:
1301 return
1302 # We have to release the lock and call self.flush() (which will
1303 # probably just re-take the lock) in case flush has been overridden in
1304 # a subclass or the user set self.flush to something. This is the same
1305 # behavior as the C implementation.
1306 try:
1307 # may raise BlockingIOError or BrokenPipeError etc
1308 self.flush()
1309 finally:
1310 with self._write_lock:
1311 self.raw.close()
1312
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001313
1314class BufferedRWPair(BufferedIOBase):
1315
1316 """A buffered reader and writer object together.
1317
1318 A buffered reader object and buffered writer object put together to
1319 form a sequential IO object that can read and write. This is typically
1320 used with a socket or two-way pipe.
1321
1322 reader and writer are RawIOBase objects that are readable and
1323 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001324 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001325 """
1326
1327 # XXX The usefulness of this (compared to having two separate IO
1328 # objects) is questionable.
1329
Florent Xicluna109d5732012-07-07 17:03:22 +02001330 def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001331 """Constructor.
1332
1333 The arguments are two RawIO instances.
1334 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001335 if not reader.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001336 raise OSError('"reader" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001337
1338 if not writer.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001339 raise OSError('"writer" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001340
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001341 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001342 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001343
Martin Panterccb2c0e2016-10-20 23:48:14 +00001344 def read(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001345 if size is None:
1346 size = -1
1347 return self.reader.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001348
1349 def readinto(self, b):
1350 return self.reader.readinto(b)
1351
1352 def write(self, b):
1353 return self.writer.write(b)
1354
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001355 def peek(self, size=0):
1356 return self.reader.peek(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001357
Martin Panterccb2c0e2016-10-20 23:48:14 +00001358 def read1(self, size=-1):
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001359 return self.reader.read1(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001360
Benjamin Petersona96fea02014-06-22 14:17:44 -07001361 def readinto1(self, b):
1362 return self.reader.readinto1(b)
1363
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001364 def readable(self):
1365 return self.reader.readable()
1366
1367 def writable(self):
1368 return self.writer.writable()
1369
1370 def flush(self):
1371 return self.writer.flush()
1372
1373 def close(self):
Serhiy Storchaka7665be62015-03-24 23:21:57 +02001374 try:
1375 self.writer.close()
1376 finally:
1377 self.reader.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001378
1379 def isatty(self):
1380 return self.reader.isatty() or self.writer.isatty()
1381
1382 @property
1383 def closed(self):
1384 return self.writer.closed
1385
1386
1387class BufferedRandom(BufferedWriter, BufferedReader):
1388
1389 """A buffered interface to random access streams.
1390
1391 The constructor creates a reader and writer for a seekable stream,
1392 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001393 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001394 """
1395
Florent Xicluna109d5732012-07-07 17:03:22 +02001396 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001397 raw._checkSeekable()
1398 BufferedReader.__init__(self, raw, buffer_size)
Florent Xicluna109d5732012-07-07 17:03:22 +02001399 BufferedWriter.__init__(self, raw, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001400
1401 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001402 if whence not in valid_seek_flags:
1403 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001404 self.flush()
1405 if self._read_buf:
1406 # Undo read ahead.
1407 with self._read_lock:
1408 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1409 # First do the raw seek, then empty the read buffer, so that
1410 # if the raw seek fails, we don't lose buffered data forever.
1411 pos = self.raw.seek(pos, whence)
1412 with self._read_lock:
1413 self._reset_read_buf()
1414 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001415 raise OSError("seek() returned invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001416 return pos
1417
1418 def tell(self):
1419 if self._write_buf:
1420 return BufferedWriter.tell(self)
1421 else:
1422 return BufferedReader.tell(self)
1423
1424 def truncate(self, pos=None):
1425 if pos is None:
1426 pos = self.tell()
1427 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001428 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001429
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001430 def read(self, size=None):
1431 if size is None:
1432 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001433 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001434 return BufferedReader.read(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001435
1436 def readinto(self, b):
1437 self.flush()
1438 return BufferedReader.readinto(self, b)
1439
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001440 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001441 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001442 return BufferedReader.peek(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001443
Martin Panterccb2c0e2016-10-20 23:48:14 +00001444 def read1(self, size=-1):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001445 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001446 return BufferedReader.read1(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001447
Benjamin Petersona96fea02014-06-22 14:17:44 -07001448 def readinto1(self, b):
1449 self.flush()
1450 return BufferedReader.readinto1(self, b)
1451
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001452 def write(self, b):
1453 if self._read_buf:
1454 # Undo readahead
1455 with self._read_lock:
1456 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1457 self._reset_read_buf()
1458 return BufferedWriter.write(self, b)
1459
1460
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001461class FileIO(RawIOBase):
1462 _fd = -1
1463 _created = False
1464 _readable = False
1465 _writable = False
1466 _appending = False
1467 _seekable = None
1468 _closefd = True
1469
1470 def __init__(self, file, mode='r', closefd=True, opener=None):
1471 """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
1472 writing, exclusive creation or appending. The file will be created if it
1473 doesn't exist when opened for writing or appending; it will be truncated
1474 when opened for writing. A FileExistsError will be raised if it already
1475 exists when opened for creating. Opening a file for creating implies
1476 writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode
1477 to allow simultaneous reading and writing. A custom opener can be used by
1478 passing a callable as *opener*. The underlying file descriptor for the file
1479 object is then obtained by calling opener with (*name*, *flags*).
1480 *opener* must return an open file descriptor (passing os.open as *opener*
1481 results in functionality similar to passing None).
1482 """
1483 if self._fd >= 0:
1484 # Have to close the existing file first.
1485 try:
1486 if self._closefd:
1487 os.close(self._fd)
1488 finally:
1489 self._fd = -1
1490
1491 if isinstance(file, float):
1492 raise TypeError('integer argument expected, got float')
1493 if isinstance(file, int):
1494 fd = file
1495 if fd < 0:
1496 raise ValueError('negative file descriptor')
1497 else:
1498 fd = -1
1499
1500 if not isinstance(mode, str):
1501 raise TypeError('invalid mode: %s' % (mode,))
1502 if not set(mode) <= set('xrwab+'):
1503 raise ValueError('invalid mode: %s' % (mode,))
1504 if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1:
1505 raise ValueError('Must have exactly one of create/read/write/append '
1506 'mode and at most one plus')
1507
1508 if 'x' in mode:
1509 self._created = True
1510 self._writable = True
1511 flags = os.O_EXCL | os.O_CREAT
1512 elif 'r' in mode:
1513 self._readable = True
1514 flags = 0
1515 elif 'w' in mode:
1516 self._writable = True
1517 flags = os.O_CREAT | os.O_TRUNC
1518 elif 'a' in mode:
1519 self._writable = True
1520 self._appending = True
1521 flags = os.O_APPEND | os.O_CREAT
1522
1523 if '+' in mode:
1524 self._readable = True
1525 self._writable = True
1526
1527 if self._readable and self._writable:
1528 flags |= os.O_RDWR
1529 elif self._readable:
1530 flags |= os.O_RDONLY
1531 else:
1532 flags |= os.O_WRONLY
1533
1534 flags |= getattr(os, 'O_BINARY', 0)
1535
1536 noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or
1537 getattr(os, 'O_CLOEXEC', 0))
1538 flags |= noinherit_flag
1539
1540 owned_fd = None
1541 try:
1542 if fd < 0:
1543 if not closefd:
1544 raise ValueError('Cannot use closefd=False with file name')
1545 if opener is None:
1546 fd = os.open(file, flags, 0o666)
1547 else:
1548 fd = opener(file, flags)
1549 if not isinstance(fd, int):
1550 raise TypeError('expected integer from opener')
1551 if fd < 0:
1552 raise OSError('Negative file descriptor')
1553 owned_fd = fd
1554 if not noinherit_flag:
1555 os.set_inheritable(fd, False)
1556
1557 self._closefd = closefd
1558 fdfstat = os.fstat(fd)
1559 try:
1560 if stat.S_ISDIR(fdfstat.st_mode):
1561 raise IsADirectoryError(errno.EISDIR,
1562 os.strerror(errno.EISDIR), file)
1563 except AttributeError:
1564 # Ignore the AttribueError if stat.S_ISDIR or errno.EISDIR
1565 # don't exist.
1566 pass
1567 self._blksize = getattr(fdfstat, 'st_blksize', 0)
1568 if self._blksize <= 1:
1569 self._blksize = DEFAULT_BUFFER_SIZE
1570
1571 if _setmode:
1572 # don't translate newlines (\r\n <=> \n)
1573 _setmode(fd, os.O_BINARY)
1574
1575 self.name = file
1576 if self._appending:
1577 # For consistent behaviour, we explicitly seek to the
1578 # end of file (otherwise, it might be done only on the
1579 # first write()).
1580 os.lseek(fd, 0, SEEK_END)
1581 except:
1582 if owned_fd is not None:
1583 os.close(owned_fd)
1584 raise
1585 self._fd = fd
1586
1587 def __del__(self):
1588 if self._fd >= 0 and self._closefd and not self.closed:
1589 import warnings
1590 warnings.warn('unclosed file %r' % (self,), ResourceWarning,
Victor Stinnere19558a2016-03-23 00:28:08 +01001591 stacklevel=2, source=self)
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001592 self.close()
1593
1594 def __getstate__(self):
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +02001595 raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
Serhiy Storchaka71fd2242015-04-10 16:16:16 +03001596
1597 def __repr__(self):
1598 class_name = '%s.%s' % (self.__class__.__module__,
1599 self.__class__.__qualname__)
1600 if self.closed:
1601 return '<%s [closed]>' % class_name
1602 try:
1603 name = self.name
1604 except AttributeError:
1605 return ('<%s fd=%d mode=%r closefd=%r>' %
1606 (class_name, self._fd, self.mode, self._closefd))
1607 else:
1608 return ('<%s name=%r mode=%r closefd=%r>' %
1609 (class_name, name, self.mode, self._closefd))
1610
1611 def _checkReadable(self):
1612 if not self._readable:
1613 raise UnsupportedOperation('File not open for reading')
1614
1615 def _checkWritable(self, msg=None):
1616 if not self._writable:
1617 raise UnsupportedOperation('File not open for writing')
1618
1619 def read(self, size=None):
1620 """Read at most size bytes, returned as bytes.
1621
1622 Only makes one system call, so less data may be returned than requested
1623 In non-blocking mode, returns None if no data is available.
1624 Return an empty bytes object at EOF.
1625 """
1626 self._checkClosed()
1627 self._checkReadable()
1628 if size is None or size < 0:
1629 return self.readall()
1630 try:
1631 return os.read(self._fd, size)
1632 except BlockingIOError:
1633 return None
1634
1635 def readall(self):
1636 """Read all data from the file, returned as bytes.
1637
1638 In non-blocking mode, returns as much as is immediately available,
1639 or None if no data is available. Return an empty bytes object at EOF.
1640 """
1641 self._checkClosed()
1642 self._checkReadable()
1643 bufsize = DEFAULT_BUFFER_SIZE
1644 try:
1645 pos = os.lseek(self._fd, 0, SEEK_CUR)
1646 end = os.fstat(self._fd).st_size
1647 if end >= pos:
1648 bufsize = end - pos + 1
1649 except OSError:
1650 pass
1651
1652 result = bytearray()
1653 while True:
1654 if len(result) >= bufsize:
1655 bufsize = len(result)
1656 bufsize += max(bufsize, DEFAULT_BUFFER_SIZE)
1657 n = bufsize - len(result)
1658 try:
1659 chunk = os.read(self._fd, n)
1660 except BlockingIOError:
1661 if result:
1662 break
1663 return None
1664 if not chunk: # reached the end of the file
1665 break
1666 result += chunk
1667
1668 return bytes(result)
1669
1670 def readinto(self, b):
1671 """Same as RawIOBase.readinto()."""
1672 m = memoryview(b).cast('B')
1673 data = self.read(len(m))
1674 n = len(data)
1675 m[:n] = data
1676 return n
1677
1678 def write(self, b):
1679 """Write bytes b to file, return number written.
1680
1681 Only makes one system call, so not all of the data may be written.
1682 The number of bytes actually written is returned. In non-blocking mode,
1683 returns None if the write would block.
1684 """
1685 self._checkClosed()
1686 self._checkWritable()
1687 try:
1688 return os.write(self._fd, b)
1689 except BlockingIOError:
1690 return None
1691
1692 def seek(self, pos, whence=SEEK_SET):
1693 """Move to new file position.
1694
1695 Argument offset is a byte count. Optional argument whence defaults to
1696 SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
1697 are SEEK_CUR or 1 (move relative to current position, positive or negative),
1698 and SEEK_END or 2 (move relative to end of file, usually negative, although
1699 many platforms allow seeking beyond the end of a file).
1700
1701 Note that not all file objects are seekable.
1702 """
1703 if isinstance(pos, float):
1704 raise TypeError('an integer is required')
1705 self._checkClosed()
1706 return os.lseek(self._fd, pos, whence)
1707
1708 def tell(self):
1709 """tell() -> int. Current file position.
1710
1711 Can raise OSError for non seekable files."""
1712 self._checkClosed()
1713 return os.lseek(self._fd, 0, SEEK_CUR)
1714
1715 def truncate(self, size=None):
1716 """Truncate the file to at most size bytes.
1717
1718 Size defaults to the current file position, as returned by tell().
1719 The current file position is changed to the value of size.
1720 """
1721 self._checkClosed()
1722 self._checkWritable()
1723 if size is None:
1724 size = self.tell()
1725 os.ftruncate(self._fd, size)
1726 return size
1727
1728 def close(self):
1729 """Close the file.
1730
1731 A closed file cannot be used for further I/O operations. close() may be
1732 called more than once without error.
1733 """
1734 if not self.closed:
1735 try:
1736 if self._closefd:
1737 os.close(self._fd)
1738 finally:
1739 super().close()
1740
1741 def seekable(self):
1742 """True if file supports random-access."""
1743 self._checkClosed()
1744 if self._seekable is None:
1745 try:
1746 self.tell()
1747 except OSError:
1748 self._seekable = False
1749 else:
1750 self._seekable = True
1751 return self._seekable
1752
1753 def readable(self):
1754 """True if file was opened in a read mode."""
1755 self._checkClosed()
1756 return self._readable
1757
1758 def writable(self):
1759 """True if file was opened in a write mode."""
1760 self._checkClosed()
1761 return self._writable
1762
1763 def fileno(self):
1764 """Return the underlying file descriptor (an integer)."""
1765 self._checkClosed()
1766 return self._fd
1767
1768 def isatty(self):
1769 """True if the file is connected to a TTY device."""
1770 self._checkClosed()
1771 return os.isatty(self._fd)
1772
1773 @property
1774 def closefd(self):
1775 """True if the file descriptor will be closed by close()."""
1776 return self._closefd
1777
1778 @property
1779 def mode(self):
1780 """String giving the file mode"""
1781 if self._created:
1782 if self._readable:
1783 return 'xb+'
1784 else:
1785 return 'xb'
1786 elif self._appending:
1787 if self._readable:
1788 return 'ab+'
1789 else:
1790 return 'ab'
1791 elif self._readable:
1792 if self._writable:
1793 return 'rb+'
1794 else:
1795 return 'rb'
1796 else:
1797 return 'wb'
1798
1799
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001800class TextIOBase(IOBase):
1801
1802 """Base class for text I/O.
1803
1804 This class provides a character and line based interface to stream
Steve Palmer7b97ab32019-04-09 05:35:27 +01001805 I/O. There is no public constructor.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001806 """
1807
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001808 def read(self, size=-1):
1809 """Read at most size characters from stream, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001810
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001811 Read from underlying buffer until we have size characters or we hit EOF.
1812 If size is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001813
1814 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001815 """
1816 self._unsupported("read")
1817
Raymond Hettinger3c940242011-01-12 23:39:31 +00001818 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001819 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001820 self._unsupported("write")
1821
Georg Brandl4d73b572011-01-13 07:13:06 +00001822 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001823 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001824 self._unsupported("truncate")
1825
Raymond Hettinger3c940242011-01-12 23:39:31 +00001826 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001827 """Read until newline or EOF.
1828
1829 Returns an empty string if EOF is hit immediately.
1830 """
1831 self._unsupported("readline")
1832
Raymond Hettinger3c940242011-01-12 23:39:31 +00001833 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001834 """
1835 Separate the underlying buffer from the TextIOBase and return it.
1836
1837 After the underlying buffer has been detached, the TextIO is in an
1838 unusable state.
1839 """
1840 self._unsupported("detach")
1841
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001842 @property
1843 def encoding(self):
1844 """Subclasses should override."""
1845 return None
1846
1847 @property
1848 def newlines(self):
1849 """Line endings translated so far.
1850
1851 Only line endings translated during reading are considered.
1852
1853 Subclasses should override.
1854 """
1855 return None
1856
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001857 @property
1858 def errors(self):
1859 """Error setting of the decoder or encoder.
1860
1861 Subclasses should override."""
1862 return None
1863
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001864io.TextIOBase.register(TextIOBase)
1865
1866
1867class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1868 r"""Codec used when reading a file in universal newlines mode. It wraps
1869 another incremental decoder, translating \r\n and \r into \n. It also
1870 records the types of newlines encountered. When used with
1871 translate=False, it ensures that the newline sequence is returned in
1872 one piece.
1873 """
1874 def __init__(self, decoder, translate, errors='strict'):
1875 codecs.IncrementalDecoder.__init__(self, errors=errors)
1876 self.translate = translate
1877 self.decoder = decoder
1878 self.seennl = 0
1879 self.pendingcr = False
1880
1881 def decode(self, input, final=False):
1882 # decode input (with the eventual \r from a previous pass)
1883 if self.decoder is None:
1884 output = input
1885 else:
1886 output = self.decoder.decode(input, final=final)
1887 if self.pendingcr and (output or final):
1888 output = "\r" + output
1889 self.pendingcr = False
1890
1891 # retain last \r even when not translating data:
1892 # then readline() is sure to get \r\n in one pass
1893 if output.endswith("\r") and not final:
1894 output = output[:-1]
1895 self.pendingcr = True
1896
1897 # Record which newlines are read
1898 crlf = output.count('\r\n')
1899 cr = output.count('\r') - crlf
1900 lf = output.count('\n') - crlf
1901 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1902 | (crlf and self._CRLF)
1903
1904 if self.translate:
1905 if crlf:
1906 output = output.replace("\r\n", "\n")
1907 if cr:
1908 output = output.replace("\r", "\n")
1909
1910 return output
1911
1912 def getstate(self):
1913 if self.decoder is None:
1914 buf = b""
1915 flag = 0
1916 else:
1917 buf, flag = self.decoder.getstate()
1918 flag <<= 1
1919 if self.pendingcr:
1920 flag |= 1
1921 return buf, flag
1922
1923 def setstate(self, state):
1924 buf, flag = state
1925 self.pendingcr = bool(flag & 1)
1926 if self.decoder is not None:
1927 self.decoder.setstate((buf, flag >> 1))
1928
1929 def reset(self):
1930 self.seennl = 0
1931 self.pendingcr = False
1932 if self.decoder is not None:
1933 self.decoder.reset()
1934
1935 _LF = 1
1936 _CR = 2
1937 _CRLF = 4
1938
1939 @property
1940 def newlines(self):
1941 return (None,
1942 "\n",
1943 "\r",
1944 ("\r", "\n"),
1945 "\r\n",
1946 ("\n", "\r\n"),
1947 ("\r", "\r\n"),
1948 ("\r", "\n", "\r\n")
1949 )[self.seennl]
1950
1951
1952class TextIOWrapper(TextIOBase):
1953
1954 r"""Character and line based layer over a BufferedIOBase object, buffer.
1955
1956 encoding gives the name of the encoding that the stream will be
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001957 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001958
1959 errors determines the strictness of encoding and decoding (see the
1960 codecs.register) and defaults to "strict".
1961
1962 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1963 handling of line endings. If it is None, universal newlines is
1964 enabled. With this enabled, on input, the lines endings '\n', '\r',
1965 or '\r\n' are translated to '\n' before being returned to the
1966 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001967 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001968 legal values, that newline becomes the newline when the file is read
1969 and it is returned untranslated. On output, '\n' is converted to the
1970 newline.
1971
1972 If line_buffering is True, a call to flush is implied when a call to
1973 write contains a newline character.
1974 """
1975
1976 _CHUNK_SIZE = 2048
1977
Victor Stinnera3568412019-05-28 01:44:21 +02001978 # Initialize _buffer as soon as possible since it's used by __del__()
1979 # which calls close()
1980 _buffer = None
1981
Andrew Svetlov4e9e9c12012-08-13 16:09:54 +03001982 # The write_through argument has no effect here since this
1983 # implementation always writes through. The argument is present only
1984 # so that the signature can match the signature of the C version.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001985 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001986 line_buffering=False, write_through=False):
INADA Naoki507434f2017-12-21 09:59:53 +09001987 self._check_newline(newline)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001988 if encoding is None:
1989 try:
1990 encoding = os.device_encoding(buffer.fileno())
1991 except (AttributeError, UnsupportedOperation):
1992 pass
1993 if encoding is None:
1994 try:
1995 import locale
Brett Cannoncd171c82013-07-04 17:43:24 -04001996 except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001997 # Importing locale may fail if Python is being built
1998 encoding = "ascii"
1999 else:
Victor Stinnerf86a5e82012-06-05 13:43:22 +02002000 encoding = locale.getpreferredencoding(False)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002001
2002 if not isinstance(encoding, str):
2003 raise ValueError("invalid encoding: %r" % encoding)
2004
Nick Coghlana9b15242014-02-04 22:11:18 +10002005 if not codecs.lookup(encoding)._is_text_encoding:
2006 msg = ("%r is not a text encoding; "
2007 "use codecs.open() to handle arbitrary codecs")
2008 raise LookupError(msg % encoding)
2009
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002010 if errors is None:
2011 errors = "strict"
2012 else:
2013 if not isinstance(errors, str):
2014 raise ValueError("invalid errors: %r" % errors)
2015
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002016 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002017 self._decoded_chars = '' # buffer for text returned from decoder
2018 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
2019 self._snapshot = None # info for reconstructing decoder state
2020 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02002021 self._has_read1 = hasattr(self.buffer, 'read1')
INADA Naoki507434f2017-12-21 09:59:53 +09002022 self._configure(encoding, errors, newline,
2023 line_buffering, write_through)
2024
2025 def _check_newline(self, newline):
2026 if newline is not None and not isinstance(newline, str):
2027 raise TypeError("illegal newline type: %r" % (type(newline),))
2028 if newline not in (None, "", "\n", "\r", "\r\n"):
2029 raise ValueError("illegal newline value: %r" % (newline,))
2030
2031 def _configure(self, encoding=None, errors=None, newline=None,
2032 line_buffering=False, write_through=False):
2033 self._encoding = encoding
2034 self._errors = errors
2035 self._encoder = None
2036 self._decoder = None
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002037 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002038
INADA Naoki507434f2017-12-21 09:59:53 +09002039 self._readuniversal = not newline
2040 self._readtranslate = newline is None
2041 self._readnl = newline
2042 self._writetranslate = newline != ''
2043 self._writenl = newline or os.linesep
2044
2045 self._line_buffering = line_buffering
2046 self._write_through = write_through
2047
2048 # don't write a BOM in the middle of a file
Antoine Pitroue4501852009-05-14 18:55:55 +00002049 if self._seekable and self.writable():
2050 position = self.buffer.tell()
2051 if position != 0:
2052 try:
2053 self._get_encoder().setstate(0)
2054 except LookupError:
2055 # Sometimes the encoder doesn't exist
2056 pass
2057
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002058 # self._snapshot is either None, or a tuple (dec_flags, next_input)
2059 # where dec_flags is the second (integer) item of the decoder state
2060 # and next_input is the chunk of input bytes that comes next after the
2061 # snapshot point. We use this to reconstruct decoder states in tell().
2062
2063 # Naming convention:
2064 # - "bytes_..." for integer variables that count input bytes
2065 # - "chars_..." for integer variables that count decoded characters
2066
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00002067 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +03002068 result = "<{}.{}".format(self.__class__.__module__,
2069 self.__class__.__qualname__)
Antoine Pitrou716c4442009-05-23 19:04:03 +00002070 try:
2071 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -06002072 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002073 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00002074 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002075 result += " name={0!r}".format(name)
2076 try:
2077 mode = self.mode
Benjamin Peterson10e76b62014-12-21 20:51:50 -06002078 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00002079 pass
2080 else:
2081 result += " mode={0!r}".format(mode)
2082 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00002083
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002084 @property
2085 def encoding(self):
2086 return self._encoding
2087
2088 @property
2089 def errors(self):
2090 return self._errors
2091
2092 @property
2093 def line_buffering(self):
2094 return self._line_buffering
2095
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002096 @property
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002097 def write_through(self):
2098 return self._write_through
2099
2100 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002101 def buffer(self):
2102 return self._buffer
2103
INADA Naoki507434f2017-12-21 09:59:53 +09002104 def reconfigure(self, *,
2105 encoding=None, errors=None, newline=Ellipsis,
2106 line_buffering=None, write_through=None):
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002107 """Reconfigure the text stream with new parameters.
2108
2109 This also flushes the stream.
2110 """
INADA Naoki507434f2017-12-21 09:59:53 +09002111 if (self._decoder is not None
2112 and (encoding is not None or errors is not None
2113 or newline is not Ellipsis)):
2114 raise UnsupportedOperation(
2115 "It is not possible to set the encoding or newline of stream "
2116 "after the first read")
2117
2118 if errors is None:
2119 if encoding is None:
2120 errors = self._errors
2121 else:
2122 errors = 'strict'
2123 elif not isinstance(errors, str):
2124 raise TypeError("invalid errors: %r" % errors)
2125
2126 if encoding is None:
2127 encoding = self._encoding
2128 else:
2129 if not isinstance(encoding, str):
2130 raise TypeError("invalid encoding: %r" % encoding)
2131
2132 if newline is Ellipsis:
2133 newline = self._readnl
2134 self._check_newline(newline)
2135
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002136 if line_buffering is None:
2137 line_buffering = self.line_buffering
2138 if write_through is None:
2139 write_through = self.write_through
INADA Naoki507434f2017-12-21 09:59:53 +09002140
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002141 self.flush()
INADA Naoki507434f2017-12-21 09:59:53 +09002142 self._configure(encoding, errors, newline,
2143 line_buffering, write_through)
Antoine Pitrou3c2817b2017-06-03 12:32:28 +02002144
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002145 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02002146 if self.closed:
2147 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002148 return self._seekable
2149
2150 def readable(self):
2151 return self.buffer.readable()
2152
2153 def writable(self):
2154 return self.buffer.writable()
2155
2156 def flush(self):
2157 self.buffer.flush()
2158 self._telling = self._seekable
2159
2160 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00002161 if self.buffer is not None and not self.closed:
Benjamin Peterson68623612012-12-20 11:53:11 -06002162 try:
2163 self.flush()
2164 finally:
2165 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002166
2167 @property
2168 def closed(self):
2169 return self.buffer.closed
2170
2171 @property
2172 def name(self):
2173 return self.buffer.name
2174
2175 def fileno(self):
2176 return self.buffer.fileno()
2177
2178 def isatty(self):
2179 return self.buffer.isatty()
2180
Raymond Hettinger00fa0392011-01-13 02:52:26 +00002181 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00002182 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002183 if self.closed:
2184 raise ValueError("write to closed file")
2185 if not isinstance(s, str):
2186 raise TypeError("can't write %s to text stream" %
2187 s.__class__.__name__)
2188 length = len(s)
2189 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
2190 if haslf and self._writetranslate and self._writenl != "\n":
2191 s = s.replace("\n", self._writenl)
2192 encoder = self._encoder or self._get_encoder()
2193 # XXX What if we were just reading?
2194 b = encoder.encode(s)
2195 self.buffer.write(b)
2196 if self._line_buffering and (haslf or "\r" in s):
2197 self.flush()
Zackery Spytz23db9352018-06-29 04:14:58 -06002198 self._set_decoded_chars('')
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002199 self._snapshot = None
2200 if self._decoder:
2201 self._decoder.reset()
2202 return length
2203
2204 def _get_encoder(self):
2205 make_encoder = codecs.getincrementalencoder(self._encoding)
2206 self._encoder = make_encoder(self._errors)
2207 return self._encoder
2208
2209 def _get_decoder(self):
2210 make_decoder = codecs.getincrementaldecoder(self._encoding)
2211 decoder = make_decoder(self._errors)
2212 if self._readuniversal:
2213 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
2214 self._decoder = decoder
2215 return decoder
2216
2217 # The following three methods implement an ADT for _decoded_chars.
2218 # Text returned from the decoder is buffered here until the client
2219 # requests it by calling our read() or readline() method.
2220 def _set_decoded_chars(self, chars):
2221 """Set the _decoded_chars buffer."""
2222 self._decoded_chars = chars
2223 self._decoded_chars_used = 0
2224
2225 def _get_decoded_chars(self, n=None):
2226 """Advance into the _decoded_chars buffer."""
2227 offset = self._decoded_chars_used
2228 if n is None:
2229 chars = self._decoded_chars[offset:]
2230 else:
2231 chars = self._decoded_chars[offset:offset + n]
2232 self._decoded_chars_used += len(chars)
2233 return chars
2234
2235 def _rewind_decoded_chars(self, n):
2236 """Rewind the _decoded_chars buffer."""
2237 if self._decoded_chars_used < n:
2238 raise AssertionError("rewind decoded_chars out of bounds")
2239 self._decoded_chars_used -= n
2240
2241 def _read_chunk(self):
2242 """
2243 Read and decode the next chunk of data from the BufferedReader.
2244 """
2245
2246 # The return value is True unless EOF was reached. The decoded
2247 # string is placed in self._decoded_chars (replacing its previous
2248 # value). The entire input chunk is sent to the decoder, though
2249 # some of it may remain buffered in the decoder, yet to be
2250 # converted.
2251
2252 if self._decoder is None:
2253 raise ValueError("no decoder")
2254
2255 if self._telling:
2256 # To prepare for tell(), we need to snapshot a point in the
2257 # file where the decoder's input buffer is empty.
2258
2259 dec_buffer, dec_flags = self._decoder.getstate()
2260 # Given this, we know there was a valid snapshot point
2261 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
2262
2263 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02002264 if self._has_read1:
2265 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
2266 else:
2267 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002268 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002269 decoded_chars = self._decoder.decode(input_chunk, eof)
2270 self._set_decoded_chars(decoded_chars)
2271 if decoded_chars:
2272 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
2273 else:
2274 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002275
2276 if self._telling:
2277 # At the snapshot point, len(dec_buffer) bytes before the read,
2278 # the next input to be decoded is dec_buffer + input_chunk.
2279 self._snapshot = (dec_flags, dec_buffer + input_chunk)
2280
2281 return not eof
2282
2283 def _pack_cookie(self, position, dec_flags=0,
2284 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
2285 # The meaning of a tell() cookie is: seek to position, set the
2286 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
2287 # into the decoder with need_eof as the EOF flag, then skip
2288 # chars_to_skip characters of the decoded result. For most simple
2289 # decoders, tell() will often just give a byte offset in the file.
2290 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
2291 (chars_to_skip<<192) | bool(need_eof)<<256)
2292
2293 def _unpack_cookie(self, bigint):
2294 rest, position = divmod(bigint, 1<<64)
2295 rest, dec_flags = divmod(rest, 1<<64)
2296 rest, bytes_to_feed = divmod(rest, 1<<64)
2297 need_eof, chars_to_skip = divmod(rest, 1<<64)
2298 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
2299
2300 def tell(self):
2301 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002302 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002303 if not self._telling:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002304 raise OSError("telling position disabled by next() call")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002305 self.flush()
2306 position = self.buffer.tell()
2307 decoder = self._decoder
2308 if decoder is None or self._snapshot is None:
2309 if self._decoded_chars:
2310 # This should never happen.
2311 raise AssertionError("pending decoded text")
2312 return position
2313
2314 # Skip backward to the snapshot point (see _read_chunk).
2315 dec_flags, next_input = self._snapshot
2316 position -= len(next_input)
2317
2318 # How many decoded characters have been used up since the snapshot?
2319 chars_to_skip = self._decoded_chars_used
2320 if chars_to_skip == 0:
2321 # We haven't moved from the snapshot point.
2322 return self._pack_cookie(position, dec_flags)
2323
2324 # Starting from the snapshot position, we will walk the decoder
2325 # forward until it gives us enough decoded characters.
2326 saved_state = decoder.getstate()
2327 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002328 # Fast search for an acceptable start point, close to our
2329 # current pos.
2330 # Rationale: calling decoder.decode() has a large overhead
2331 # regardless of chunk size; we want the number of such calls to
Raymond Hettinger14010182018-09-13 21:17:40 -07002332 # be O(1) in most situations (common decoders, sensible input).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002333 # Actually, it will be exactly 1 for fixed-size codecs (all
2334 # 8-bit codecs, also UTF-16 and UTF-32).
2335 skip_bytes = int(self._b2cratio * chars_to_skip)
2336 skip_back = 1
2337 assert skip_bytes <= len(next_input)
2338 while skip_bytes > 0:
2339 decoder.setstate((b'', dec_flags))
2340 # Decode up to temptative start point
2341 n = len(decoder.decode(next_input[:skip_bytes]))
2342 if n <= chars_to_skip:
2343 b, d = decoder.getstate()
2344 if not b:
2345 # Before pos and no bytes buffered in decoder => OK
2346 dec_flags = d
2347 chars_to_skip -= n
2348 break
2349 # Skip back by buffered amount and reset heuristic
2350 skip_bytes -= len(b)
2351 skip_back = 1
2352 else:
2353 # We're too far ahead, skip back a bit
2354 skip_bytes -= skip_back
2355 skip_back = skip_back * 2
2356 else:
2357 skip_bytes = 0
2358 decoder.setstate((b'', dec_flags))
2359
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002360 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002361 start_pos = position + skip_bytes
2362 start_flags = dec_flags
2363 if chars_to_skip == 0:
2364 # We haven't moved from the start point.
2365 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002366
2367 # Feed the decoder one byte at a time. As we go, note the
2368 # nearest "safe start point" before the current location
2369 # (a point where the decoder has nothing buffered, so seek()
2370 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002371 bytes_fed = 0
2372 need_eof = 0
2373 # Chars decoded since `start_pos`
2374 chars_decoded = 0
2375 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002376 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00002377 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002378 dec_buffer, dec_flags = decoder.getstate()
2379 if not dec_buffer and chars_decoded <= chars_to_skip:
2380 # Decoder buffer is empty, so this is a safe start point.
2381 start_pos += bytes_fed
2382 chars_to_skip -= chars_decoded
2383 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
2384 if chars_decoded >= chars_to_skip:
2385 break
2386 else:
2387 # We didn't get enough decoded data; signal EOF to get more.
2388 chars_decoded += len(decoder.decode(b'', final=True))
2389 need_eof = 1
2390 if chars_decoded < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002391 raise OSError("can't reconstruct logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002392
2393 # The returned cookie corresponds to the last safe start point.
2394 return self._pack_cookie(
2395 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
2396 finally:
2397 decoder.setstate(saved_state)
2398
2399 def truncate(self, pos=None):
2400 self.flush()
2401 if pos is None:
2402 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00002403 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002404
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002405 def detach(self):
2406 if self.buffer is None:
2407 raise ValueError("buffer is already detached")
2408 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00002409 buffer = self._buffer
2410 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002411 return buffer
2412
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002413 def seek(self, cookie, whence=0):
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002414 def _reset_encoder(position):
2415 """Reset the encoder (merely useful for proper BOM handling)"""
2416 try:
2417 encoder = self._encoder or self._get_encoder()
2418 except LookupError:
2419 # Sometimes the encoder doesn't exist
2420 pass
2421 else:
2422 if position != 0:
2423 encoder.setstate(0)
2424 else:
2425 encoder.reset()
2426
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002427 if self.closed:
2428 raise ValueError("tell on closed file")
2429 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002430 raise UnsupportedOperation("underlying stream is not seekable")
ngie-eign848037c2019-03-02 23:28:26 -08002431 if whence == SEEK_CUR:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002432 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002433 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002434 # Seeking to the current position should attempt to
2435 # sync the underlying buffer with the current position.
2436 whence = 0
2437 cookie = self.tell()
ngie-eign848037c2019-03-02 23:28:26 -08002438 elif whence == SEEK_END:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002439 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00002440 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002441 self.flush()
ngie-eign848037c2019-03-02 23:28:26 -08002442 position = self.buffer.seek(0, whence)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002443 self._set_decoded_chars('')
2444 self._snapshot = None
2445 if self._decoder:
2446 self._decoder.reset()
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002447 _reset_encoder(position)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002448 return position
2449 if whence != 0:
Jesus Cea94363612012-06-22 18:32:07 +02002450 raise ValueError("unsupported whence (%r)" % (whence,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002451 if cookie < 0:
2452 raise ValueError("negative seek position %r" % (cookie,))
2453 self.flush()
2454
2455 # The strategy of seek() is to go back to the safe start point
2456 # and replay the effect of read(chars_to_skip) from there.
2457 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
2458 self._unpack_cookie(cookie)
2459
2460 # Seek back to the safe start point.
2461 self.buffer.seek(start_pos)
2462 self._set_decoded_chars('')
2463 self._snapshot = None
2464
2465 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00002466 if cookie == 0 and self._decoder:
2467 self._decoder.reset()
2468 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002469 self._decoder = self._decoder or self._get_decoder()
2470 self._decoder.setstate((b'', dec_flags))
2471 self._snapshot = (dec_flags, b'')
2472
2473 if chars_to_skip:
2474 # Just like _read_chunk, feed the decoder and save a snapshot.
2475 input_chunk = self.buffer.read(bytes_to_feed)
2476 self._set_decoded_chars(
2477 self._decoder.decode(input_chunk, need_eof))
2478 self._snapshot = (dec_flags, input_chunk)
2479
2480 # Skip chars_to_skip of the decoded characters.
2481 if len(self._decoded_chars) < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002482 raise OSError("can't restore logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002483 self._decoded_chars_used = chars_to_skip
2484
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02002485 _reset_encoder(cookie)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002486 return cookie
2487
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002488 def read(self, size=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00002489 self._checkReadable()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002490 if size is None:
2491 size = -1
Oren Milmande503602017-08-24 21:33:42 +03002492 else:
2493 try:
2494 size_index = size.__index__
2495 except AttributeError:
2496 raise TypeError(f"{size!r} is not an integer")
2497 else:
2498 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002499 decoder = self._decoder or self._get_decoder()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002500 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002501 # Read everything.
2502 result = (self._get_decoded_chars() +
2503 decoder.decode(self.buffer.read(), final=True))
2504 self._set_decoded_chars('')
2505 self._snapshot = None
2506 return result
2507 else:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002508 # Keep reading chunks until we have size characters to return.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002509 eof = False
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002510 result = self._get_decoded_chars(size)
2511 while len(result) < size and not eof:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002512 eof = not self._read_chunk()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002513 result += self._get_decoded_chars(size - len(result))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002514 return result
2515
2516 def __next__(self):
2517 self._telling = False
2518 line = self.readline()
2519 if not line:
2520 self._snapshot = None
2521 self._telling = self._seekable
2522 raise StopIteration
2523 return line
2524
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002525 def readline(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002526 if self.closed:
2527 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002528 if size is None:
2529 size = -1
Oren Milmande503602017-08-24 21:33:42 +03002530 else:
2531 try:
2532 size_index = size.__index__
2533 except AttributeError:
2534 raise TypeError(f"{size!r} is not an integer")
2535 else:
2536 size = size_index()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002537
2538 # Grab all the decoded text (we will rewind any extra bits later).
2539 line = self._get_decoded_chars()
2540
2541 start = 0
2542 # Make the decoder if it doesn't already exist.
2543 if not self._decoder:
2544 self._get_decoder()
2545
2546 pos = endpos = None
2547 while True:
2548 if self._readtranslate:
2549 # Newlines are already translated, only search for \n
2550 pos = line.find('\n', start)
2551 if pos >= 0:
2552 endpos = pos + 1
2553 break
2554 else:
2555 start = len(line)
2556
2557 elif self._readuniversal:
2558 # Universal newline search. Find any of \r, \r\n, \n
2559 # The decoder ensures that \r\n are not split in two pieces
2560
2561 # In C we'd look for these in parallel of course.
2562 nlpos = line.find("\n", start)
2563 crpos = line.find("\r", start)
2564 if crpos == -1:
2565 if nlpos == -1:
2566 # Nothing found
2567 start = len(line)
2568 else:
2569 # Found \n
2570 endpos = nlpos + 1
2571 break
2572 elif nlpos == -1:
2573 # Found lone \r
2574 endpos = crpos + 1
2575 break
2576 elif nlpos < crpos:
2577 # Found \n
2578 endpos = nlpos + 1
2579 break
2580 elif nlpos == crpos + 1:
2581 # Found \r\n
2582 endpos = crpos + 2
2583 break
2584 else:
2585 # Found \r
2586 endpos = crpos + 1
2587 break
2588 else:
2589 # non-universal
2590 pos = line.find(self._readnl)
2591 if pos >= 0:
2592 endpos = pos + len(self._readnl)
2593 break
2594
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002595 if size >= 0 and len(line) >= size:
2596 endpos = size # reached length size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002597 break
2598
2599 # No line ending seen yet - get more data'
2600 while self._read_chunk():
2601 if self._decoded_chars:
2602 break
2603 if self._decoded_chars:
2604 line += self._get_decoded_chars()
2605 else:
2606 # end of file
2607 self._set_decoded_chars('')
2608 self._snapshot = None
2609 return line
2610
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002611 if size >= 0 and endpos > size:
2612 endpos = size # don't exceed size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002613
2614 # Rewind _decoded_chars to just after the line ending we found.
2615 self._rewind_decoded_chars(len(line) - endpos)
2616 return line[:endpos]
2617
2618 @property
2619 def newlines(self):
2620 return self._decoder.newlines if self._decoder else None
2621
2622
2623class StringIO(TextIOWrapper):
2624 """Text I/O implementation using an in-memory buffer.
2625
2626 The initial_value argument sets the value of object. The newline
2627 argument is like the one of TextIOWrapper's constructor.
2628 """
2629
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002630 def __init__(self, initial_value="", newline="\n"):
2631 super(StringIO, self).__init__(BytesIO(),
2632 encoding="utf-8",
Serhiy Storchakac92ea762014-01-29 11:33:26 +02002633 errors="surrogatepass",
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002634 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002635 # Issue #5645: make universal newlines semantics the same as in the
2636 # C version, even under Windows.
2637 if newline is None:
2638 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002639 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002640 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002641 raise TypeError("initial_value must be str or None, not {0}"
2642 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002643 self.write(initial_value)
2644 self.seek(0)
2645
2646 def getvalue(self):
2647 self.flush()
Antoine Pitrou57839a62014-02-02 23:37:29 +01002648 decoder = self._decoder or self._get_decoder()
2649 old_state = decoder.getstate()
2650 decoder.reset()
2651 try:
2652 return decoder.decode(self.buffer.getvalue(), final=True)
2653 finally:
2654 decoder.setstate(old_state)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002655
2656 def __repr__(self):
2657 # TextIOWrapper tells the encoding in its repr. In StringIO,
Martin Panter7462b6492015-11-02 03:37:02 +00002658 # that's an implementation detail.
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002659 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002660
2661 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002662 def errors(self):
2663 return None
2664
2665 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002666 def encoding(self):
2667 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002668
2669 def detach(self):
2670 # This doesn't make sense on StringIO.
2671 self._unsupported("detach")