blob: 1df44ccbba77b931b152819c4e93a84e2e1b8745 [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
Benjamin Petersona96fea02014-06-22 14:17:44 -07009import array
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000010# Import _thread instead of threading to reduce startup cost
11try:
12 from _thread import allocate_lock as Lock
Brett Cannoncd171c82013-07-04 17:43:24 -040013except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000014 from _dummy_thread import allocate_lock as Lock
15
16import io
Benjamin Petersonc3be11a2010-04-27 21:24:03 +000017from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000018
Jesus Cea94363612012-06-22 18:32:07 +020019valid_seek_flags = {0, 1, 2} # Hardwired values
20if hasattr(os, 'SEEK_HOLE') :
21 valid_seek_flags.add(os.SEEK_HOLE)
22 valid_seek_flags.add(os.SEEK_DATA)
23
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000024# open() uses st_blksize whenever we can
25DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
26
27# NOTE: Base classes defined here are registered with the "official" ABCs
Benjamin Peterson86fdbf32015-03-18 21:35:38 -050028# defined in io.py. We don't use real inheritance though, because we don't want
29# to inherit the C implementations.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000030
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020031# Rebind for compatibility
32BlockingIOError = BlockingIOError
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000033
34
Georg Brandl4d73b572011-01-13 07:13:06 +000035def open(file, mode="r", buffering=-1, encoding=None, errors=None,
Ross Lagerwall59142db2011-10-31 20:34:46 +020036 newline=None, closefd=True, opener=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000037
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020038 r"""Open file and return a stream. Raise OSError upon failure.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000039
40 file is either a text or byte string giving the name (and the path
41 if the file isn't in the current working directory) of the file to
42 be opened or an integer file descriptor of the file to be
43 wrapped. (If a file descriptor is given, it is closed when the
44 returned I/O object is closed, unless closefd is set to False.)
45
Charles-François Natalidc3044c2012-01-09 22:40:02 +010046 mode is an optional string that specifies the mode in which the file is
47 opened. It defaults to 'r' which means open for reading in text mode. Other
48 common values are 'w' for writing (truncating the file if it already
Charles-François Natalid612de12012-01-14 11:51:00 +010049 exists), 'x' for exclusive creation of a new file, and 'a' for appending
Charles-François Natalidc3044c2012-01-09 22:40:02 +010050 (which on some Unix systems, means that all writes append to the end of the
51 file regardless of the current seek position). In text mode, if encoding is
52 not specified the encoding used is platform dependent. (For reading and
53 writing raw bytes use binary mode and leave encoding unspecified.) The
54 available modes are:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000055
56 ========= ===============================================================
57 Character Meaning
58 --------- ---------------------------------------------------------------
59 'r' open for reading (default)
60 'w' open for writing, truncating the file first
Charles-François Natalidc3044c2012-01-09 22:40:02 +010061 'x' create a new file and open it for writing
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000062 'a' open for writing, appending to the end of the file if it exists
63 'b' binary mode
64 't' text mode (default)
65 '+' open a disk file for updating (reading and writing)
Serhiy Storchaka6787a382013-11-23 22:12:06 +020066 'U' universal newline mode (deprecated)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000067 ========= ===============================================================
68
69 The default mode is 'rt' (open for reading text). For binary random
70 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
Charles-François Natalidc3044c2012-01-09 22:40:02 +010071 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
72 raises an `FileExistsError` if the file already exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000073
74 Python distinguishes between files opened in binary and text modes,
75 even when the underlying operating system doesn't. Files opened in
76 binary mode (appending 'b' to the mode argument) return contents as
77 bytes objects without any decoding. In text mode (the default, or when
78 't' is appended to the mode argument), the contents of the file are
79 returned as strings, the bytes having been first decoded using a
80 platform-dependent encoding or using the specified encoding if given.
81
Serhiy Storchaka6787a382013-11-23 22:12:06 +020082 'U' mode is deprecated and will raise an exception in future versions
83 of Python. It has no effect in Python 3. Use newline to control
84 universal newlines mode.
85
Antoine Pitroud5587bc2009-12-19 21:08:31 +000086 buffering is an optional integer used to set the buffering policy.
87 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
88 line buffering (only usable in text mode), and an integer > 1 to indicate
89 the size of a fixed-size chunk buffer. When no buffering argument is
90 given, the default buffering policy works as follows:
91
92 * Binary files are buffered in fixed-size chunks; the size of the buffer
93 is chosen using a heuristic trying to determine the underlying device's
94 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
95 On many systems, the buffer will typically be 4096 or 8192 bytes long.
96
97 * "Interactive" text files (files for which isatty() returns True)
98 use line buffering. Other text files use the policy described above
99 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000100
Raymond Hettingercbb80892011-01-13 18:15:51 +0000101 encoding is the str name of the encoding used to decode or encode the
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000102 file. This should only be used in text mode. The default encoding is
103 platform dependent, but any encoding supported by Python can be
104 passed. See the codecs module for the list of supported encodings.
105
106 errors is an optional string that specifies how encoding errors are to
107 be handled---this argument should not be used in binary mode. Pass
108 'strict' to raise a ValueError exception if there is an encoding error
109 (the default of None has the same effect), or pass 'ignore' to ignore
110 errors. (Note that ignoring encoding errors can lead to data loss.)
111 See the documentation for codecs.register for a list of the permitted
112 encoding error strings.
113
Raymond Hettingercbb80892011-01-13 18:15:51 +0000114 newline is a string controlling how universal newlines works (it only
115 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
116 as follows:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000117
118 * On input, if newline is None, universal newlines mode is
119 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
120 these are translated into '\n' before being returned to the
121 caller. If it is '', universal newline mode is enabled, but line
122 endings are returned to the caller untranslated. If it has any of
123 the other legal values, input lines are only terminated by the given
124 string, and the line ending is returned to the caller untranslated.
125
126 * On output, if newline is None, any '\n' characters written are
127 translated to the system default line separator, os.linesep. If
128 newline is '', no translation takes place. If newline is any of the
129 other legal values, any '\n' characters written are translated to
130 the given string.
131
Raymond Hettingercbb80892011-01-13 18:15:51 +0000132 closedfd is a bool. If closefd is False, the underlying file descriptor will
133 be kept open when the file is closed. This does not work when a file name is
134 given and must be True in that case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000135
Victor Stinnerdaf45552013-08-28 00:53:59 +0200136 The newly created file is non-inheritable.
137
Ross Lagerwall59142db2011-10-31 20:34:46 +0200138 A custom opener can be used by passing a callable as *opener*. The
139 underlying file descriptor for the file object is then obtained by calling
140 *opener* with (*file*, *flags*). *opener* must return an open file
141 descriptor (passing os.open as *opener* results in functionality similar to
142 passing None).
143
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000144 open() returns a file object whose type depends on the mode, and
145 through which the standard file operations such as reading and writing
146 are performed. When open() is used to open a file in a text mode ('w',
147 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
148 a file in a binary mode, the returned class varies: in read binary
149 mode, it returns a BufferedReader; in write binary and append binary
150 modes, it returns a BufferedWriter, and in read/write mode, it returns
151 a BufferedRandom.
152
153 It is also possible to use a string or bytearray as a file for both
154 reading and writing. For strings StringIO can be used like a file
155 opened in a text mode, and for bytes a BytesIO can be used like a file
156 opened in a binary mode.
157 """
158 if not isinstance(file, (str, bytes, int)):
159 raise TypeError("invalid file: %r" % file)
160 if not isinstance(mode, str):
161 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000162 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000163 raise TypeError("invalid buffering: %r" % buffering)
164 if encoding is not None and not isinstance(encoding, str):
165 raise TypeError("invalid encoding: %r" % encoding)
166 if errors is not None and not isinstance(errors, str):
167 raise TypeError("invalid errors: %r" % errors)
168 modes = set(mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100169 if modes - set("axrwb+tU") or len(mode) > len(modes):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000170 raise ValueError("invalid mode: %r" % mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100171 creating = "x" in modes
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000172 reading = "r" in modes
173 writing = "w" in modes
174 appending = "a" in modes
175 updating = "+" in modes
176 text = "t" in modes
177 binary = "b" in modes
178 if "U" in modes:
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100179 if creating or writing or appending:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000180 raise ValueError("can't use U and writing mode at once")
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200181 import warnings
182 warnings.warn("'U' mode is deprecated",
183 DeprecationWarning, 2)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000184 reading = True
185 if text and binary:
186 raise ValueError("can't have text and binary mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100187 if creating + reading + writing + appending > 1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000188 raise ValueError("can't have read/write/append mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100189 if not (creating or reading or writing or appending):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000190 raise ValueError("must have exactly one of read/write/append mode")
191 if binary and encoding is not None:
192 raise ValueError("binary mode doesn't take an encoding argument")
193 if binary and errors is not None:
194 raise ValueError("binary mode doesn't take an errors argument")
195 if binary and newline is not None:
196 raise ValueError("binary mode doesn't take a newline argument")
197 raw = FileIO(file,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100198 (creating and "x" or "") +
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000199 (reading and "r" or "") +
200 (writing and "w" or "") +
201 (appending and "a" or "") +
202 (updating and "+" or ""),
Ross Lagerwall59142db2011-10-31 20:34:46 +0200203 closefd, opener=opener)
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300204 result = raw
205 try:
206 line_buffering = False
207 if buffering == 1 or buffering < 0 and raw.isatty():
208 buffering = -1
209 line_buffering = True
210 if buffering < 0:
211 buffering = DEFAULT_BUFFER_SIZE
212 try:
213 bs = os.fstat(raw.fileno()).st_blksize
214 except (OSError, AttributeError):
215 pass
216 else:
217 if bs > 1:
218 buffering = bs
219 if buffering < 0:
220 raise ValueError("invalid buffering size")
221 if buffering == 0:
222 if binary:
223 return result
224 raise ValueError("can't have unbuffered text I/O")
225 if updating:
226 buffer = BufferedRandom(raw, buffering)
227 elif creating or writing or appending:
228 buffer = BufferedWriter(raw, buffering)
229 elif reading:
230 buffer = BufferedReader(raw, buffering)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000231 else:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300232 raise ValueError("unknown mode: %r" % mode)
233 result = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000234 if binary:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300235 return result
236 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
237 result = text
238 text.mode = mode
239 return result
240 except:
241 result.close()
242 raise
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000243
244
245class DocDescriptor:
246 """Helper for builtins.open.__doc__
247 """
248 def __get__(self, obj, typ):
249 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000250 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000251 "errors=None, newline=None, closefd=True)\n\n" +
252 open.__doc__)
253
254class OpenWrapper:
255 """Wrapper for builtins.open
256
257 Trick so that open won't become a bound method when stored
258 as a class variable (as dbm.dumb does).
259
Nick Coghland6009512014-11-20 21:39:37 +1000260 See initstdio() in Python/pylifecycle.c.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000261 """
262 __doc__ = DocDescriptor()
263
264 def __new__(cls, *args, **kwargs):
265 return open(*args, **kwargs)
266
267
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000268# In normal operation, both `UnsupportedOperation`s should be bound to the
269# same object.
270try:
271 UnsupportedOperation = io.UnsupportedOperation
272except AttributeError:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200273 class UnsupportedOperation(ValueError, OSError):
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000274 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000275
276
277class IOBase(metaclass=abc.ABCMeta):
278
279 """The abstract base class for all I/O classes, acting on streams of
280 bytes. There is no public constructor.
281
282 This class provides dummy implementations for many methods that
283 derived classes can override selectively; the default implementations
284 represent a file that cannot be read, written or seeked.
285
286 Even though IOBase does not declare read, readinto, or write because
287 their signatures will vary, implementations and clients should
288 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000289 may raise UnsupportedOperation when operations they do not support are
290 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000291
292 The basic type used for binary data read from or written to a file is
293 bytes. bytearrays are accepted too, and in some cases (such as
294 readinto) needed. Text I/O classes work with str data.
295
296 Note that calling any method (even inquiries) on a closed stream is
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200297 undefined. Implementations may raise OSError in this case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000298
299 IOBase (and its subclasses) support the iterator protocol, meaning
300 that an IOBase object can be iterated over yielding the lines in a
301 stream.
302
303 IOBase also supports the :keyword:`with` statement. In this example,
304 fp is closed after the suite of the with statement is complete:
305
306 with open('spam.txt', 'r') as fp:
307 fp.write('Spam and eggs!')
308 """
309
310 ### Internal ###
311
Raymond Hettinger3c940242011-01-12 23:39:31 +0000312 def _unsupported(self, name):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200313 """Internal: raise an OSError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000314 raise UnsupportedOperation("%s.%s() not supported" %
315 (self.__class__.__name__, name))
316
317 ### Positioning ###
318
Georg Brandl4d73b572011-01-13 07:13:06 +0000319 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000320 """Change stream position.
321
Terry Jan Reedyc30b7b12013-03-11 17:57:08 -0400322 Change the stream position to byte offset pos. Argument pos is
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000323 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000324 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000325
326 * 0 -- start of stream (the default); offset should be zero or positive
327 * 1 -- current stream position; offset may be negative
328 * 2 -- end of stream; offset is usually negative
Jesus Cea94363612012-06-22 18:32:07 +0200329 Some operating systems / file systems could provide additional values.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000330
Raymond Hettingercbb80892011-01-13 18:15:51 +0000331 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000332 """
333 self._unsupported("seek")
334
Raymond Hettinger3c940242011-01-12 23:39:31 +0000335 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000336 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000337 return self.seek(0, 1)
338
Georg Brandl4d73b572011-01-13 07:13:06 +0000339 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000340 """Truncate file to size bytes.
341
342 Size defaults to the current IO position as reported by tell(). Return
343 the new size.
344 """
345 self._unsupported("truncate")
346
347 ### Flush and close ###
348
Raymond Hettinger3c940242011-01-12 23:39:31 +0000349 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000350 """Flush write buffers, if applicable.
351
352 This is not implemented for read-only and non-blocking streams.
353 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000354 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000355 # XXX Should this return the number of bytes written???
356
357 __closed = False
358
Raymond Hettinger3c940242011-01-12 23:39:31 +0000359 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000360 """Flush and close the IO object.
361
362 This method has no effect if the file is already closed.
363 """
364 if not self.__closed:
Benjamin Peterson68623612012-12-20 11:53:11 -0600365 try:
366 self.flush()
367 finally:
368 self.__closed = True
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000369
Raymond Hettinger3c940242011-01-12 23:39:31 +0000370 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000371 """Destructor. Calls close()."""
372 # The try/except block is in case this is called at program
373 # exit time, when it's possible that globals have already been
374 # deleted, and then the close() call might fail. Since
375 # there's nothing we can do about such failures and they annoy
376 # the end users, we suppress the traceback.
377 try:
378 self.close()
379 except:
380 pass
381
382 ### Inquiries ###
383
Raymond Hettinger3c940242011-01-12 23:39:31 +0000384 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000385 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000386
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000387 If False, seek(), tell() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000388 This method may need to do a test seek().
389 """
390 return False
391
392 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000393 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000394 """
395 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000396 raise UnsupportedOperation("File or stream is not seekable."
397 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000398
Raymond Hettinger3c940242011-01-12 23:39:31 +0000399 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000400 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000401
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000402 If False, read() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000403 """
404 return False
405
406 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000407 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000408 """
409 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000410 raise UnsupportedOperation("File or stream is not readable."
411 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000412
Raymond Hettinger3c940242011-01-12 23:39:31 +0000413 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000414 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000415
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000416 If False, write() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000417 """
418 return False
419
420 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000421 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000422 """
423 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000424 raise UnsupportedOperation("File or stream is not writable."
425 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000426
427 @property
428 def closed(self):
429 """closed: bool. True iff the file has been closed.
430
431 For backwards compatibility, this is a property, not a predicate.
432 """
433 return self.__closed
434
435 def _checkClosed(self, msg=None):
436 """Internal: raise an ValueError if file is closed
437 """
438 if self.closed:
439 raise ValueError("I/O operation on closed file."
440 if msg is None else msg)
441
442 ### Context manager ###
443
Raymond Hettinger3c940242011-01-12 23:39:31 +0000444 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000445 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000446 self._checkClosed()
447 return self
448
Raymond Hettinger3c940242011-01-12 23:39:31 +0000449 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000450 """Context management protocol. Calls close()"""
451 self.close()
452
453 ### Lower-level APIs ###
454
455 # XXX Should these be present even if unimplemented?
456
Raymond Hettinger3c940242011-01-12 23:39:31 +0000457 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000458 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000459
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200460 An OSError is raised if the IO object does not use a file descriptor.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000461 """
462 self._unsupported("fileno")
463
Raymond Hettinger3c940242011-01-12 23:39:31 +0000464 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000465 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000466
467 Return False if it can't be determined.
468 """
469 self._checkClosed()
470 return False
471
472 ### Readline[s] and writelines ###
473
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300474 def readline(self, size=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000475 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000476
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300477 If size is specified, at most size bytes will be read.
478 Size should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000479
480 The line terminator is always b'\n' for binary files; for text
481 files, the newlines argument to open can be used to select the line
482 terminator(s) recognized.
483 """
484 # For backwards compatibility, a (slowish) readline().
485 if hasattr(self, "peek"):
486 def nreadahead():
487 readahead = self.peek(1)
488 if not readahead:
489 return 1
490 n = (readahead.find(b"\n") + 1) or len(readahead)
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300491 if size >= 0:
492 n = min(n, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000493 return n
494 else:
495 def nreadahead():
496 return 1
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300497 if size is None:
498 size = -1
499 elif not isinstance(size, int):
500 raise TypeError("size must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000501 res = bytearray()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300502 while size < 0 or len(res) < size:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000503 b = self.read(nreadahead())
504 if not b:
505 break
506 res += b
507 if res.endswith(b"\n"):
508 break
509 return bytes(res)
510
511 def __iter__(self):
512 self._checkClosed()
513 return self
514
515 def __next__(self):
516 line = self.readline()
517 if not line:
518 raise StopIteration
519 return line
520
521 def readlines(self, hint=None):
522 """Return a list of lines from the stream.
523
524 hint can be specified to control the number of lines read: no more
525 lines will be read if the total size (in bytes/characters) of all
526 lines so far exceeds hint.
527 """
528 if hint is None or hint <= 0:
529 return list(self)
530 n = 0
531 lines = []
532 for line in self:
533 lines.append(line)
534 n += len(line)
535 if n >= hint:
536 break
537 return lines
538
539 def writelines(self, lines):
540 self._checkClosed()
541 for line in lines:
542 self.write(line)
543
544io.IOBase.register(IOBase)
545
546
547class RawIOBase(IOBase):
548
549 """Base class for raw binary I/O."""
550
551 # The read() method is implemented by calling readinto(); derived
552 # classes that want to support read() only need to implement
553 # readinto() as a primitive operation. In general, readinto() can be
554 # more efficient than read().
555
556 # (It would be tempting to also provide an implementation of
557 # readinto() in terms of read(), in case the latter is a more suitable
558 # primitive operation, but that would lead to nasty recursion in case
559 # a subclass doesn't implement either.)
560
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300561 def read(self, size=-1):
562 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000563
564 Returns an empty bytes object on EOF, or None if the object is
565 set not to block and has no data to read.
566 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300567 if size is None:
568 size = -1
569 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000570 return self.readall()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300571 b = bytearray(size.__index__())
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000572 n = self.readinto(b)
Antoine Pitrou328ec742010-09-14 18:37:24 +0000573 if n is None:
574 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000575 del b[n:]
576 return bytes(b)
577
578 def readall(self):
579 """Read until EOF, using multiple read() call."""
580 res = bytearray()
581 while True:
582 data = self.read(DEFAULT_BUFFER_SIZE)
583 if not data:
584 break
585 res += data
Victor Stinnera80987f2011-05-25 22:47:16 +0200586 if res:
587 return bytes(res)
588 else:
589 # b'' or None
590 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000591
Raymond Hettinger3c940242011-01-12 23:39:31 +0000592 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000593 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000594
Raymond Hettingercbb80892011-01-13 18:15:51 +0000595 Returns an int representing the number of bytes read (0 for EOF), or
596 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000597 """
598 self._unsupported("readinto")
599
Raymond Hettinger3c940242011-01-12 23:39:31 +0000600 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000601 """Write the given buffer to the IO stream.
602
603 Returns the number of bytes written, which may be less than len(b).
604 """
605 self._unsupported("write")
606
607io.RawIOBase.register(RawIOBase)
608from _io import FileIO
609RawIOBase.register(FileIO)
610
611
612class BufferedIOBase(IOBase):
613
614 """Base class for buffered IO objects.
615
616 The main difference with RawIOBase is that the read() method
617 supports omitting the size argument, and does not have a default
618 implementation that defers to readinto().
619
620 In addition, read(), readinto() and write() may raise
621 BlockingIOError if the underlying raw stream is in non-blocking
622 mode and not ready; unlike their raw counterparts, they will never
623 return None.
624
625 A typical implementation should not inherit from a RawIOBase
626 implementation, but wrap one.
627 """
628
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300629 def read(self, size=None):
630 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000631
632 If the argument is omitted, None, or negative, reads and
633 returns all data until EOF.
634
635 If the argument is positive, and the underlying raw stream is
636 not 'interactive', multiple raw reads may be issued to satisfy
637 the byte count (unless EOF is reached first). But for
638 interactive raw streams (XXX and for pipes?), at most one raw
639 read will be issued, and a short result does not imply that
640 EOF is imminent.
641
642 Returns an empty bytes array on EOF.
643
644 Raises BlockingIOError if the underlying raw stream has no
645 data at the moment.
646 """
647 self._unsupported("read")
648
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300649 def read1(self, size=None):
650 """Read up to size bytes with at most one read() system call,
651 where size is an int.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000652 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000653 self._unsupported("read1")
654
Raymond Hettinger3c940242011-01-12 23:39:31 +0000655 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000656 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000657
658 Like read(), this may issue multiple reads to the underlying raw
659 stream, unless the latter is 'interactive'.
660
Raymond Hettingercbb80892011-01-13 18:15:51 +0000661 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000662
663 Raises BlockingIOError if the underlying raw stream has no
664 data at the moment.
665 """
Benjamin Petersona96fea02014-06-22 14:17:44 -0700666
667 return self._readinto(b, read1=False)
668
669 def readinto1(self, b):
670 """Read up to len(b) bytes into *b*, using at most one system call
671
672 Returns an int representing the number of bytes read (0 for EOF).
673
674 Raises BlockingIOError if the underlying raw stream has no
675 data at the moment.
676 """
677
678 return self._readinto(b, read1=True)
679
680 def _readinto(self, b, read1):
681 if not isinstance(b, memoryview):
682 b = memoryview(b)
683 b = b.cast('B')
684
685 if read1:
686 data = self.read1(len(b))
687 else:
688 data = self.read(len(b))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000689 n = len(data)
Benjamin Petersona96fea02014-06-22 14:17:44 -0700690
691 b[:n] = data
692
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000693 return n
694
Raymond Hettinger3c940242011-01-12 23:39:31 +0000695 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000696 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000697
698 Return the number of bytes written, which is never less than
699 len(b).
700
701 Raises BlockingIOError if the buffer is full and the
702 underlying raw stream cannot accept more data at the moment.
703 """
704 self._unsupported("write")
705
Raymond Hettinger3c940242011-01-12 23:39:31 +0000706 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000707 """
708 Separate the underlying raw stream from the buffer and return it.
709
710 After the raw stream has been detached, the buffer is in an unusable
711 state.
712 """
713 self._unsupported("detach")
714
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000715io.BufferedIOBase.register(BufferedIOBase)
716
717
718class _BufferedIOMixin(BufferedIOBase):
719
720 """A mixin implementation of BufferedIOBase with an underlying raw stream.
721
722 This passes most requests on to the underlying raw stream. It
723 does *not* provide implementations of read(), readinto() or
724 write().
725 """
726
727 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000728 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000729
730 ### Positioning ###
731
732 def seek(self, pos, whence=0):
733 new_position = self.raw.seek(pos, whence)
734 if new_position < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200735 raise OSError("seek() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000736 return new_position
737
738 def tell(self):
739 pos = self.raw.tell()
740 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200741 raise OSError("tell() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000742 return pos
743
744 def truncate(self, pos=None):
745 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
746 # and a flush may be necessary to synch both views of the current
747 # file state.
748 self.flush()
749
750 if pos is None:
751 pos = self.tell()
752 # XXX: Should seek() be used, instead of passing the position
753 # XXX directly to truncate?
754 return self.raw.truncate(pos)
755
756 ### Flush and close ###
757
758 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000759 if self.closed:
760 raise ValueError("flush of closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000761 self.raw.flush()
762
763 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000764 if self.raw is not None and not self.closed:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +0100765 try:
766 # may raise BlockingIOError or BrokenPipeError etc
767 self.flush()
768 finally:
769 self.raw.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000770
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000771 def detach(self):
772 if self.raw is None:
773 raise ValueError("raw stream already detached")
774 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000775 raw = self._raw
776 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000777 return raw
778
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000779 ### Inquiries ###
780
781 def seekable(self):
782 return self.raw.seekable()
783
784 def readable(self):
785 return self.raw.readable()
786
787 def writable(self):
788 return self.raw.writable()
789
790 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000791 def raw(self):
792 return self._raw
793
794 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000795 def closed(self):
796 return self.raw.closed
797
798 @property
799 def name(self):
800 return self.raw.name
801
802 @property
803 def mode(self):
804 return self.raw.mode
805
Antoine Pitrou243757e2010-11-05 21:15:39 +0000806 def __getstate__(self):
807 raise TypeError("can not serialize a '{0}' object"
808 .format(self.__class__.__name__))
809
Antoine Pitrou716c4442009-05-23 19:04:03 +0000810 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300811 modname = self.__class__.__module__
812 clsname = self.__class__.__qualname__
Antoine Pitrou716c4442009-05-23 19:04:03 +0000813 try:
814 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -0600815 except Exception:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300816 return "<{}.{}>".format(modname, clsname)
Antoine Pitrou716c4442009-05-23 19:04:03 +0000817 else:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300818 return "<{}.{} name={!r}>".format(modname, clsname, name)
Antoine Pitrou716c4442009-05-23 19:04:03 +0000819
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000820 ### Lower-level APIs ###
821
822 def fileno(self):
823 return self.raw.fileno()
824
825 def isatty(self):
826 return self.raw.isatty()
827
828
829class BytesIO(BufferedIOBase):
830
831 """Buffered I/O implementation using an in-memory bytes buffer."""
832
833 def __init__(self, initial_bytes=None):
834 buf = bytearray()
835 if initial_bytes is not None:
836 buf += initial_bytes
837 self._buffer = buf
838 self._pos = 0
839
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000840 def __getstate__(self):
841 if self.closed:
842 raise ValueError("__getstate__ on closed file")
843 return self.__dict__.copy()
844
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000845 def getvalue(self):
846 """Return the bytes value (contents) of the buffer
847 """
848 if self.closed:
849 raise ValueError("getvalue on closed file")
850 return bytes(self._buffer)
851
Antoine Pitrou972ee132010-09-06 18:48:21 +0000852 def getbuffer(self):
853 """Return a readable and writable view of the buffer.
854 """
Serhiy Storchakac057c382015-02-03 02:00:18 +0200855 if self.closed:
856 raise ValueError("getbuffer on closed file")
Antoine Pitrou972ee132010-09-06 18:48:21 +0000857 return memoryview(self._buffer)
858
Serhiy Storchakac057c382015-02-03 02:00:18 +0200859 def close(self):
860 self._buffer.clear()
861 super().close()
862
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300863 def read(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000864 if self.closed:
865 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300866 if size is None:
867 size = -1
868 if size < 0:
869 size = len(self._buffer)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000870 if len(self._buffer) <= self._pos:
871 return b""
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300872 newpos = min(len(self._buffer), self._pos + size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000873 b = self._buffer[self._pos : newpos]
874 self._pos = newpos
875 return bytes(b)
876
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300877 def read1(self, size):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000878 """This is the same as read.
879 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300880 return self.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000881
882 def write(self, b):
883 if self.closed:
884 raise ValueError("write to closed file")
885 if isinstance(b, str):
886 raise TypeError("can't write str to binary stream")
887 n = len(b)
888 if n == 0:
889 return 0
890 pos = self._pos
891 if pos > len(self._buffer):
892 # Inserts null bytes between the current end of the file
893 # and the new write position.
894 padding = b'\x00' * (pos - len(self._buffer))
895 self._buffer += padding
896 self._buffer[pos:pos + n] = b
897 self._pos += n
898 return n
899
900 def seek(self, pos, whence=0):
901 if self.closed:
902 raise ValueError("seek on closed file")
903 try:
Florent Xiclunab14930c2010-03-13 15:26:44 +0000904 pos.__index__
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000905 except AttributeError as err:
906 raise TypeError("an integer is required") from err
907 if whence == 0:
908 if pos < 0:
909 raise ValueError("negative seek position %r" % (pos,))
910 self._pos = pos
911 elif whence == 1:
912 self._pos = max(0, self._pos + pos)
913 elif whence == 2:
914 self._pos = max(0, len(self._buffer) + pos)
915 else:
Jesus Cea94363612012-06-22 18:32:07 +0200916 raise ValueError("unsupported whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000917 return self._pos
918
919 def tell(self):
920 if self.closed:
921 raise ValueError("tell on closed file")
922 return self._pos
923
924 def truncate(self, pos=None):
925 if self.closed:
926 raise ValueError("truncate on closed file")
927 if pos is None:
928 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000929 else:
930 try:
931 pos.__index__
932 except AttributeError as err:
933 raise TypeError("an integer is required") from err
934 if pos < 0:
935 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000936 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000937 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000938
939 def readable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200940 if self.closed:
941 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000942 return True
943
944 def writable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200945 if self.closed:
946 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000947 return True
948
949 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200950 if self.closed:
951 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000952 return True
953
954
955class BufferedReader(_BufferedIOMixin):
956
957 """BufferedReader(raw[, buffer_size])
958
959 A buffer for a readable, sequential BaseRawIO object.
960
961 The constructor creates a BufferedReader for the given readable raw
962 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
963 is used.
964 """
965
966 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
967 """Create a new buffered reader using the given readable raw IO object.
968 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000969 if not raw.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200970 raise OSError('"raw" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000971
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000972 _BufferedIOMixin.__init__(self, raw)
973 if buffer_size <= 0:
974 raise ValueError("invalid buffer size")
975 self.buffer_size = buffer_size
976 self._reset_read_buf()
977 self._read_lock = Lock()
978
979 def _reset_read_buf(self):
980 self._read_buf = b""
981 self._read_pos = 0
982
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300983 def read(self, size=None):
984 """Read size bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000985
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300986 Returns exactly size bytes of data unless the underlying raw IO
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000987 stream reaches EOF or if the call would block in non-blocking
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300988 mode. If size is negative, read until EOF or until read() would
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000989 block.
990 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300991 if size is not None and size < -1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000992 raise ValueError("invalid number of bytes to read")
993 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300994 return self._read_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000995
996 def _read_unlocked(self, n=None):
997 nodata_val = b""
998 empty_values = (b"", None)
999 buf = self._read_buf
1000 pos = self._read_pos
1001
1002 # Special case for when the number of bytes to read is unspecified.
1003 if n is None or n == -1:
1004 self._reset_read_buf()
Victor Stinnerb57f1082011-05-26 00:19:38 +02001005 if hasattr(self.raw, 'readall'):
1006 chunk = self.raw.readall()
1007 if chunk is None:
1008 return buf[pos:] or None
1009 else:
1010 return buf[pos:] + chunk
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001011 chunks = [buf[pos:]] # Strip the consumed bytes.
1012 current_size = 0
1013 while True:
1014 # Read until EOF or until read() would block.
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001015 chunk = self.raw.read()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001016 if chunk in empty_values:
1017 nodata_val = chunk
1018 break
1019 current_size += len(chunk)
1020 chunks.append(chunk)
1021 return b"".join(chunks) or nodata_val
1022
1023 # The number of bytes to read is specified, return at most n bytes.
1024 avail = len(buf) - pos # Length of the available buffered data.
1025 if n <= avail:
1026 # Fast path: the data to read is fully buffered.
1027 self._read_pos += n
1028 return buf[pos:pos+n]
1029 # Slow path: read from the stream until enough bytes are read,
1030 # or until an EOF occurs or until read() would block.
1031 chunks = [buf[pos:]]
1032 wanted = max(self.buffer_size, n)
1033 while avail < n:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001034 chunk = self.raw.read(wanted)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001035 if chunk in empty_values:
1036 nodata_val = chunk
1037 break
1038 avail += len(chunk)
1039 chunks.append(chunk)
1040 # n is more then avail only when an EOF occurred or when
1041 # read() would have blocked.
1042 n = min(n, avail)
1043 out = b"".join(chunks)
1044 self._read_buf = out[n:] # Save the extra data in the buffer.
1045 self._read_pos = 0
1046 return out[:n] if out else nodata_val
1047
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001048 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001049 """Returns buffered bytes without advancing the position.
1050
1051 The argument indicates a desired minimal number of bytes; we
1052 do at most one raw read to satisfy it. We never return more
1053 than self.buffer_size.
1054 """
1055 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001056 return self._peek_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001057
1058 def _peek_unlocked(self, n=0):
1059 want = min(n, self.buffer_size)
1060 have = len(self._read_buf) - self._read_pos
1061 if have < want or have <= 0:
1062 to_read = self.buffer_size - have
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001063 current = self.raw.read(to_read)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001064 if current:
1065 self._read_buf = self._read_buf[self._read_pos:] + current
1066 self._read_pos = 0
1067 return self._read_buf[self._read_pos:]
1068
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001069 def read1(self, size):
1070 """Reads up to size bytes, with at most one read() system call."""
1071 # Returns up to size bytes. If at least one byte is buffered, we
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001072 # only return buffered bytes. Otherwise, we do one raw read.
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001073 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001074 raise ValueError("number of bytes to read must be positive")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001075 if size == 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001076 return b""
1077 with self._read_lock:
1078 self._peek_unlocked(1)
1079 return self._read_unlocked(
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001080 min(size, len(self._read_buf) - self._read_pos))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001081
Benjamin Petersona96fea02014-06-22 14:17:44 -07001082 # Implementing readinto() and readinto1() is not strictly necessary (we
1083 # could rely on the base class that provides an implementation in terms of
1084 # read() and read1()). We do it anyway to keep the _pyio implementation
1085 # similar to the io implementation (which implements the methods for
1086 # performance reasons).
1087 def _readinto(self, buf, read1):
1088 """Read data into *buf* with at most one system call."""
1089
1090 if len(buf) == 0:
1091 return 0
1092
1093 # Need to create a memoryview object of type 'b', otherwise
1094 # we may not be able to assign bytes to it, and slicing it
1095 # would create a new object.
1096 if not isinstance(buf, memoryview):
1097 buf = memoryview(buf)
1098 buf = buf.cast('B')
1099
1100 written = 0
1101 with self._read_lock:
1102 while written < len(buf):
1103
1104 # First try to read from internal buffer
1105 avail = min(len(self._read_buf) - self._read_pos, len(buf))
1106 if avail:
1107 buf[written:written+avail] = \
1108 self._read_buf[self._read_pos:self._read_pos+avail]
1109 self._read_pos += avail
1110 written += avail
1111 if written == len(buf):
1112 break
1113
1114 # If remaining space in callers buffer is larger than
1115 # internal buffer, read directly into callers buffer
1116 if len(buf) - written > self.buffer_size:
1117 n = self.raw.readinto(buf[written:])
1118 if not n:
1119 break # eof
1120 written += n
1121
1122 # Otherwise refill internal buffer - unless we're
1123 # in read1 mode and already got some data
1124 elif not (read1 and written):
1125 if not self._peek_unlocked(1):
1126 break # eof
1127
1128 # In readinto1 mode, return as soon as we have some data
1129 if read1 and written:
1130 break
1131
1132 return written
1133
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001134 def tell(self):
1135 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1136
1137 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001138 if whence not in valid_seek_flags:
Jesus Cea990eff02012-04-26 17:05:31 +02001139 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001140 with self._read_lock:
1141 if whence == 1:
1142 pos -= len(self._read_buf) - self._read_pos
1143 pos = _BufferedIOMixin.seek(self, pos, whence)
1144 self._reset_read_buf()
1145 return pos
1146
1147class BufferedWriter(_BufferedIOMixin):
1148
1149 """A buffer for a writeable sequential RawIO object.
1150
1151 The constructor creates a BufferedWriter for the given writeable raw
1152 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001153 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001154 """
1155
Florent Xicluna109d5732012-07-07 17:03:22 +02001156 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001157 if not raw.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001158 raise OSError('"raw" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001159
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001160 _BufferedIOMixin.__init__(self, raw)
1161 if buffer_size <= 0:
1162 raise ValueError("invalid buffer size")
1163 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001164 self._write_buf = bytearray()
1165 self._write_lock = Lock()
1166
1167 def write(self, b):
1168 if self.closed:
1169 raise ValueError("write to closed file")
1170 if isinstance(b, str):
1171 raise TypeError("can't write str to binary stream")
1172 with self._write_lock:
1173 # XXX we can implement some more tricks to try and avoid
1174 # partial writes
1175 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001176 # We're full, so let's pre-flush the buffer. (This may
1177 # raise BlockingIOError with characters_written == 0.)
1178 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001179 before = len(self._write_buf)
1180 self._write_buf.extend(b)
1181 written = len(self._write_buf) - before
1182 if len(self._write_buf) > self.buffer_size:
1183 try:
1184 self._flush_unlocked()
1185 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001186 if len(self._write_buf) > self.buffer_size:
1187 # We've hit the buffer_size. We have to accept a partial
1188 # write and cut back our buffer.
1189 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001190 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001191 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001192 raise BlockingIOError(e.errno, e.strerror, written)
1193 return written
1194
1195 def truncate(self, pos=None):
1196 with self._write_lock:
1197 self._flush_unlocked()
1198 if pos is None:
1199 pos = self.raw.tell()
1200 return self.raw.truncate(pos)
1201
1202 def flush(self):
1203 with self._write_lock:
1204 self._flush_unlocked()
1205
1206 def _flush_unlocked(self):
1207 if self.closed:
1208 raise ValueError("flush of closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001209 while self._write_buf:
1210 try:
1211 n = self.raw.write(self._write_buf)
1212 except BlockingIOError:
1213 raise RuntimeError("self.raw should implement RawIOBase: it "
1214 "should not raise BlockingIOError")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001215 if n is None:
1216 raise BlockingIOError(
1217 errno.EAGAIN,
1218 "write could not complete without blocking", 0)
1219 if n > len(self._write_buf) or n < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001220 raise OSError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001221 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001222
1223 def tell(self):
1224 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1225
1226 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001227 if whence not in valid_seek_flags:
1228 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001229 with self._write_lock:
1230 self._flush_unlocked()
1231 return _BufferedIOMixin.seek(self, pos, whence)
1232
1233
1234class BufferedRWPair(BufferedIOBase):
1235
1236 """A buffered reader and writer object together.
1237
1238 A buffered reader object and buffered writer object put together to
1239 form a sequential IO object that can read and write. This is typically
1240 used with a socket or two-way pipe.
1241
1242 reader and writer are RawIOBase objects that are readable and
1243 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001244 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001245 """
1246
1247 # XXX The usefulness of this (compared to having two separate IO
1248 # objects) is questionable.
1249
Florent Xicluna109d5732012-07-07 17:03:22 +02001250 def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001251 """Constructor.
1252
1253 The arguments are two RawIO instances.
1254 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001255 if not reader.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001256 raise OSError('"reader" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001257
1258 if not writer.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001259 raise OSError('"writer" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001260
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001261 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001262 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001263
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001264 def read(self, size=None):
1265 if size is None:
1266 size = -1
1267 return self.reader.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001268
1269 def readinto(self, b):
1270 return self.reader.readinto(b)
1271
1272 def write(self, b):
1273 return self.writer.write(b)
1274
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001275 def peek(self, size=0):
1276 return self.reader.peek(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001277
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001278 def read1(self, size):
1279 return self.reader.read1(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001280
Benjamin Petersona96fea02014-06-22 14:17:44 -07001281 def readinto1(self, b):
1282 return self.reader.readinto1(b)
1283
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001284 def readable(self):
1285 return self.reader.readable()
1286
1287 def writable(self):
1288 return self.writer.writable()
1289
1290 def flush(self):
1291 return self.writer.flush()
1292
1293 def close(self):
Serhiy Storchaka7665be62015-03-24 23:21:57 +02001294 try:
1295 self.writer.close()
1296 finally:
1297 self.reader.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001298
1299 def isatty(self):
1300 return self.reader.isatty() or self.writer.isatty()
1301
1302 @property
1303 def closed(self):
1304 return self.writer.closed
1305
1306
1307class BufferedRandom(BufferedWriter, BufferedReader):
1308
1309 """A buffered interface to random access streams.
1310
1311 The constructor creates a reader and writer for a seekable stream,
1312 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001313 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001314 """
1315
Florent Xicluna109d5732012-07-07 17:03:22 +02001316 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001317 raw._checkSeekable()
1318 BufferedReader.__init__(self, raw, buffer_size)
Florent Xicluna109d5732012-07-07 17:03:22 +02001319 BufferedWriter.__init__(self, raw, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001320
1321 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001322 if whence not in valid_seek_flags:
1323 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001324 self.flush()
1325 if self._read_buf:
1326 # Undo read ahead.
1327 with self._read_lock:
1328 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1329 # First do the raw seek, then empty the read buffer, so that
1330 # if the raw seek fails, we don't lose buffered data forever.
1331 pos = self.raw.seek(pos, whence)
1332 with self._read_lock:
1333 self._reset_read_buf()
1334 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001335 raise OSError("seek() returned invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001336 return pos
1337
1338 def tell(self):
1339 if self._write_buf:
1340 return BufferedWriter.tell(self)
1341 else:
1342 return BufferedReader.tell(self)
1343
1344 def truncate(self, pos=None):
1345 if pos is None:
1346 pos = self.tell()
1347 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001348 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001349
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001350 def read(self, size=None):
1351 if size is None:
1352 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001353 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001354 return BufferedReader.read(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001355
1356 def readinto(self, b):
1357 self.flush()
1358 return BufferedReader.readinto(self, b)
1359
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001360 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001361 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001362 return BufferedReader.peek(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001363
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001364 def read1(self, size):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001365 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001366 return BufferedReader.read1(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001367
Benjamin Petersona96fea02014-06-22 14:17:44 -07001368 def readinto1(self, b):
1369 self.flush()
1370 return BufferedReader.readinto1(self, b)
1371
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001372 def write(self, b):
1373 if self._read_buf:
1374 # Undo readahead
1375 with self._read_lock:
1376 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1377 self._reset_read_buf()
1378 return BufferedWriter.write(self, b)
1379
1380
1381class TextIOBase(IOBase):
1382
1383 """Base class for text I/O.
1384
1385 This class provides a character and line based interface to stream
1386 I/O. There is no readinto method because Python's character strings
1387 are immutable. There is no public constructor.
1388 """
1389
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001390 def read(self, size=-1):
1391 """Read at most size characters from stream, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001392
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001393 Read from underlying buffer until we have size characters or we hit EOF.
1394 If size is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001395
1396 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001397 """
1398 self._unsupported("read")
1399
Raymond Hettinger3c940242011-01-12 23:39:31 +00001400 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001401 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001402 self._unsupported("write")
1403
Georg Brandl4d73b572011-01-13 07:13:06 +00001404 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001405 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001406 self._unsupported("truncate")
1407
Raymond Hettinger3c940242011-01-12 23:39:31 +00001408 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001409 """Read until newline or EOF.
1410
1411 Returns an empty string if EOF is hit immediately.
1412 """
1413 self._unsupported("readline")
1414
Raymond Hettinger3c940242011-01-12 23:39:31 +00001415 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001416 """
1417 Separate the underlying buffer from the TextIOBase and return it.
1418
1419 After the underlying buffer has been detached, the TextIO is in an
1420 unusable state.
1421 """
1422 self._unsupported("detach")
1423
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001424 @property
1425 def encoding(self):
1426 """Subclasses should override."""
1427 return None
1428
1429 @property
1430 def newlines(self):
1431 """Line endings translated so far.
1432
1433 Only line endings translated during reading are considered.
1434
1435 Subclasses should override.
1436 """
1437 return None
1438
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001439 @property
1440 def errors(self):
1441 """Error setting of the decoder or encoder.
1442
1443 Subclasses should override."""
1444 return None
1445
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001446io.TextIOBase.register(TextIOBase)
1447
1448
1449class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1450 r"""Codec used when reading a file in universal newlines mode. It wraps
1451 another incremental decoder, translating \r\n and \r into \n. It also
1452 records the types of newlines encountered. When used with
1453 translate=False, it ensures that the newline sequence is returned in
1454 one piece.
1455 """
1456 def __init__(self, decoder, translate, errors='strict'):
1457 codecs.IncrementalDecoder.__init__(self, errors=errors)
1458 self.translate = translate
1459 self.decoder = decoder
1460 self.seennl = 0
1461 self.pendingcr = False
1462
1463 def decode(self, input, final=False):
1464 # decode input (with the eventual \r from a previous pass)
1465 if self.decoder is None:
1466 output = input
1467 else:
1468 output = self.decoder.decode(input, final=final)
1469 if self.pendingcr and (output or final):
1470 output = "\r" + output
1471 self.pendingcr = False
1472
1473 # retain last \r even when not translating data:
1474 # then readline() is sure to get \r\n in one pass
1475 if output.endswith("\r") and not final:
1476 output = output[:-1]
1477 self.pendingcr = True
1478
1479 # Record which newlines are read
1480 crlf = output.count('\r\n')
1481 cr = output.count('\r') - crlf
1482 lf = output.count('\n') - crlf
1483 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1484 | (crlf and self._CRLF)
1485
1486 if self.translate:
1487 if crlf:
1488 output = output.replace("\r\n", "\n")
1489 if cr:
1490 output = output.replace("\r", "\n")
1491
1492 return output
1493
1494 def getstate(self):
1495 if self.decoder is None:
1496 buf = b""
1497 flag = 0
1498 else:
1499 buf, flag = self.decoder.getstate()
1500 flag <<= 1
1501 if self.pendingcr:
1502 flag |= 1
1503 return buf, flag
1504
1505 def setstate(self, state):
1506 buf, flag = state
1507 self.pendingcr = bool(flag & 1)
1508 if self.decoder is not None:
1509 self.decoder.setstate((buf, flag >> 1))
1510
1511 def reset(self):
1512 self.seennl = 0
1513 self.pendingcr = False
1514 if self.decoder is not None:
1515 self.decoder.reset()
1516
1517 _LF = 1
1518 _CR = 2
1519 _CRLF = 4
1520
1521 @property
1522 def newlines(self):
1523 return (None,
1524 "\n",
1525 "\r",
1526 ("\r", "\n"),
1527 "\r\n",
1528 ("\n", "\r\n"),
1529 ("\r", "\r\n"),
1530 ("\r", "\n", "\r\n")
1531 )[self.seennl]
1532
1533
1534class TextIOWrapper(TextIOBase):
1535
1536 r"""Character and line based layer over a BufferedIOBase object, buffer.
1537
1538 encoding gives the name of the encoding that the stream will be
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001539 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001540
1541 errors determines the strictness of encoding and decoding (see the
1542 codecs.register) and defaults to "strict".
1543
1544 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1545 handling of line endings. If it is None, universal newlines is
1546 enabled. With this enabled, on input, the lines endings '\n', '\r',
1547 or '\r\n' are translated to '\n' before being returned to the
1548 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001549 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001550 legal values, that newline becomes the newline when the file is read
1551 and it is returned untranslated. On output, '\n' is converted to the
1552 newline.
1553
1554 If line_buffering is True, a call to flush is implied when a call to
1555 write contains a newline character.
1556 """
1557
1558 _CHUNK_SIZE = 2048
1559
Andrew Svetlov4e9e9c12012-08-13 16:09:54 +03001560 # The write_through argument has no effect here since this
1561 # implementation always writes through. The argument is present only
1562 # so that the signature can match the signature of the C version.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001563 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001564 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001565 if newline is not None and not isinstance(newline, str):
1566 raise TypeError("illegal newline type: %r" % (type(newline),))
1567 if newline not in (None, "", "\n", "\r", "\r\n"):
1568 raise ValueError("illegal newline value: %r" % (newline,))
1569 if encoding is None:
1570 try:
1571 encoding = os.device_encoding(buffer.fileno())
1572 except (AttributeError, UnsupportedOperation):
1573 pass
1574 if encoding is None:
1575 try:
1576 import locale
Brett Cannoncd171c82013-07-04 17:43:24 -04001577 except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001578 # Importing locale may fail if Python is being built
1579 encoding = "ascii"
1580 else:
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001581 encoding = locale.getpreferredencoding(False)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001582
1583 if not isinstance(encoding, str):
1584 raise ValueError("invalid encoding: %r" % encoding)
1585
Nick Coghlana9b15242014-02-04 22:11:18 +10001586 if not codecs.lookup(encoding)._is_text_encoding:
1587 msg = ("%r is not a text encoding; "
1588 "use codecs.open() to handle arbitrary codecs")
1589 raise LookupError(msg % encoding)
1590
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001591 if errors is None:
1592 errors = "strict"
1593 else:
1594 if not isinstance(errors, str):
1595 raise ValueError("invalid errors: %r" % errors)
1596
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001597 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001598 self._line_buffering = line_buffering
1599 self._encoding = encoding
1600 self._errors = errors
1601 self._readuniversal = not newline
1602 self._readtranslate = newline is None
1603 self._readnl = newline
1604 self._writetranslate = newline != ''
1605 self._writenl = newline or os.linesep
1606 self._encoder = None
1607 self._decoder = None
1608 self._decoded_chars = '' # buffer for text returned from decoder
1609 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1610 self._snapshot = None # info for reconstructing decoder state
1611 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001612 self._has_read1 = hasattr(self.buffer, 'read1')
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001613 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001614
Antoine Pitroue4501852009-05-14 18:55:55 +00001615 if self._seekable and self.writable():
1616 position = self.buffer.tell()
1617 if position != 0:
1618 try:
1619 self._get_encoder().setstate(0)
1620 except LookupError:
1621 # Sometimes the encoder doesn't exist
1622 pass
1623
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001624 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1625 # where dec_flags is the second (integer) item of the decoder state
1626 # and next_input is the chunk of input bytes that comes next after the
1627 # snapshot point. We use this to reconstruct decoder states in tell().
1628
1629 # Naming convention:
1630 # - "bytes_..." for integer variables that count input bytes
1631 # - "chars_..." for integer variables that count decoded characters
1632
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001633 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +03001634 result = "<{}.{}".format(self.__class__.__module__,
1635 self.__class__.__qualname__)
Antoine Pitrou716c4442009-05-23 19:04:03 +00001636 try:
1637 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -06001638 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001639 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00001640 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001641 result += " name={0!r}".format(name)
1642 try:
1643 mode = self.mode
Benjamin Peterson10e76b62014-12-21 20:51:50 -06001644 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001645 pass
1646 else:
1647 result += " mode={0!r}".format(mode)
1648 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001649
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001650 @property
1651 def encoding(self):
1652 return self._encoding
1653
1654 @property
1655 def errors(self):
1656 return self._errors
1657
1658 @property
1659 def line_buffering(self):
1660 return self._line_buffering
1661
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001662 @property
1663 def buffer(self):
1664 return self._buffer
1665
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001666 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02001667 if self.closed:
1668 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001669 return self._seekable
1670
1671 def readable(self):
1672 return self.buffer.readable()
1673
1674 def writable(self):
1675 return self.buffer.writable()
1676
1677 def flush(self):
1678 self.buffer.flush()
1679 self._telling = self._seekable
1680
1681 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00001682 if self.buffer is not None and not self.closed:
Benjamin Peterson68623612012-12-20 11:53:11 -06001683 try:
1684 self.flush()
1685 finally:
1686 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001687
1688 @property
1689 def closed(self):
1690 return self.buffer.closed
1691
1692 @property
1693 def name(self):
1694 return self.buffer.name
1695
1696 def fileno(self):
1697 return self.buffer.fileno()
1698
1699 def isatty(self):
1700 return self.buffer.isatty()
1701
Raymond Hettinger00fa0392011-01-13 02:52:26 +00001702 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001703 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001704 if self.closed:
1705 raise ValueError("write to closed file")
1706 if not isinstance(s, str):
1707 raise TypeError("can't write %s to text stream" %
1708 s.__class__.__name__)
1709 length = len(s)
1710 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1711 if haslf and self._writetranslate and self._writenl != "\n":
1712 s = s.replace("\n", self._writenl)
1713 encoder = self._encoder or self._get_encoder()
1714 # XXX What if we were just reading?
1715 b = encoder.encode(s)
1716 self.buffer.write(b)
1717 if self._line_buffering and (haslf or "\r" in s):
1718 self.flush()
1719 self._snapshot = None
1720 if self._decoder:
1721 self._decoder.reset()
1722 return length
1723
1724 def _get_encoder(self):
1725 make_encoder = codecs.getincrementalencoder(self._encoding)
1726 self._encoder = make_encoder(self._errors)
1727 return self._encoder
1728
1729 def _get_decoder(self):
1730 make_decoder = codecs.getincrementaldecoder(self._encoding)
1731 decoder = make_decoder(self._errors)
1732 if self._readuniversal:
1733 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1734 self._decoder = decoder
1735 return decoder
1736
1737 # The following three methods implement an ADT for _decoded_chars.
1738 # Text returned from the decoder is buffered here until the client
1739 # requests it by calling our read() or readline() method.
1740 def _set_decoded_chars(self, chars):
1741 """Set the _decoded_chars buffer."""
1742 self._decoded_chars = chars
1743 self._decoded_chars_used = 0
1744
1745 def _get_decoded_chars(self, n=None):
1746 """Advance into the _decoded_chars buffer."""
1747 offset = self._decoded_chars_used
1748 if n is None:
1749 chars = self._decoded_chars[offset:]
1750 else:
1751 chars = self._decoded_chars[offset:offset + n]
1752 self._decoded_chars_used += len(chars)
1753 return chars
1754
1755 def _rewind_decoded_chars(self, n):
1756 """Rewind the _decoded_chars buffer."""
1757 if self._decoded_chars_used < n:
1758 raise AssertionError("rewind decoded_chars out of bounds")
1759 self._decoded_chars_used -= n
1760
1761 def _read_chunk(self):
1762 """
1763 Read and decode the next chunk of data from the BufferedReader.
1764 """
1765
1766 # The return value is True unless EOF was reached. The decoded
1767 # string is placed in self._decoded_chars (replacing its previous
1768 # value). The entire input chunk is sent to the decoder, though
1769 # some of it may remain buffered in the decoder, yet to be
1770 # converted.
1771
1772 if self._decoder is None:
1773 raise ValueError("no decoder")
1774
1775 if self._telling:
1776 # To prepare for tell(), we need to snapshot a point in the
1777 # file where the decoder's input buffer is empty.
1778
1779 dec_buffer, dec_flags = self._decoder.getstate()
1780 # Given this, we know there was a valid snapshot point
1781 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1782
1783 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02001784 if self._has_read1:
1785 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1786 else:
1787 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001788 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001789 decoded_chars = self._decoder.decode(input_chunk, eof)
1790 self._set_decoded_chars(decoded_chars)
1791 if decoded_chars:
1792 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
1793 else:
1794 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001795
1796 if self._telling:
1797 # At the snapshot point, len(dec_buffer) bytes before the read,
1798 # the next input to be decoded is dec_buffer + input_chunk.
1799 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1800
1801 return not eof
1802
1803 def _pack_cookie(self, position, dec_flags=0,
1804 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1805 # The meaning of a tell() cookie is: seek to position, set the
1806 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1807 # into the decoder with need_eof as the EOF flag, then skip
1808 # chars_to_skip characters of the decoded result. For most simple
1809 # decoders, tell() will often just give a byte offset in the file.
1810 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1811 (chars_to_skip<<192) | bool(need_eof)<<256)
1812
1813 def _unpack_cookie(self, bigint):
1814 rest, position = divmod(bigint, 1<<64)
1815 rest, dec_flags = divmod(rest, 1<<64)
1816 rest, bytes_to_feed = divmod(rest, 1<<64)
1817 need_eof, chars_to_skip = divmod(rest, 1<<64)
1818 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1819
1820 def tell(self):
1821 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001822 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001823 if not self._telling:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001824 raise OSError("telling position disabled by next() call")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001825 self.flush()
1826 position = self.buffer.tell()
1827 decoder = self._decoder
1828 if decoder is None or self._snapshot is None:
1829 if self._decoded_chars:
1830 # This should never happen.
1831 raise AssertionError("pending decoded text")
1832 return position
1833
1834 # Skip backward to the snapshot point (see _read_chunk).
1835 dec_flags, next_input = self._snapshot
1836 position -= len(next_input)
1837
1838 # How many decoded characters have been used up since the snapshot?
1839 chars_to_skip = self._decoded_chars_used
1840 if chars_to_skip == 0:
1841 # We haven't moved from the snapshot point.
1842 return self._pack_cookie(position, dec_flags)
1843
1844 # Starting from the snapshot position, we will walk the decoder
1845 # forward until it gives us enough decoded characters.
1846 saved_state = decoder.getstate()
1847 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001848 # Fast search for an acceptable start point, close to our
1849 # current pos.
1850 # Rationale: calling decoder.decode() has a large overhead
1851 # regardless of chunk size; we want the number of such calls to
1852 # be O(1) in most situations (common decoders, non-crazy input).
1853 # Actually, it will be exactly 1 for fixed-size codecs (all
1854 # 8-bit codecs, also UTF-16 and UTF-32).
1855 skip_bytes = int(self._b2cratio * chars_to_skip)
1856 skip_back = 1
1857 assert skip_bytes <= len(next_input)
1858 while skip_bytes > 0:
1859 decoder.setstate((b'', dec_flags))
1860 # Decode up to temptative start point
1861 n = len(decoder.decode(next_input[:skip_bytes]))
1862 if n <= chars_to_skip:
1863 b, d = decoder.getstate()
1864 if not b:
1865 # Before pos and no bytes buffered in decoder => OK
1866 dec_flags = d
1867 chars_to_skip -= n
1868 break
1869 # Skip back by buffered amount and reset heuristic
1870 skip_bytes -= len(b)
1871 skip_back = 1
1872 else:
1873 # We're too far ahead, skip back a bit
1874 skip_bytes -= skip_back
1875 skip_back = skip_back * 2
1876 else:
1877 skip_bytes = 0
1878 decoder.setstate((b'', dec_flags))
1879
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001880 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001881 start_pos = position + skip_bytes
1882 start_flags = dec_flags
1883 if chars_to_skip == 0:
1884 # We haven't moved from the start point.
1885 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001886
1887 # Feed the decoder one byte at a time. As we go, note the
1888 # nearest "safe start point" before the current location
1889 # (a point where the decoder has nothing buffered, so seek()
1890 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001891 bytes_fed = 0
1892 need_eof = 0
1893 # Chars decoded since `start_pos`
1894 chars_decoded = 0
1895 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001896 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001897 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001898 dec_buffer, dec_flags = decoder.getstate()
1899 if not dec_buffer and chars_decoded <= chars_to_skip:
1900 # Decoder buffer is empty, so this is a safe start point.
1901 start_pos += bytes_fed
1902 chars_to_skip -= chars_decoded
1903 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1904 if chars_decoded >= chars_to_skip:
1905 break
1906 else:
1907 # We didn't get enough decoded data; signal EOF to get more.
1908 chars_decoded += len(decoder.decode(b'', final=True))
1909 need_eof = 1
1910 if chars_decoded < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001911 raise OSError("can't reconstruct logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001912
1913 # The returned cookie corresponds to the last safe start point.
1914 return self._pack_cookie(
1915 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1916 finally:
1917 decoder.setstate(saved_state)
1918
1919 def truncate(self, pos=None):
1920 self.flush()
1921 if pos is None:
1922 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001923 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001924
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001925 def detach(self):
1926 if self.buffer is None:
1927 raise ValueError("buffer is already detached")
1928 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001929 buffer = self._buffer
1930 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001931 return buffer
1932
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001933 def seek(self, cookie, whence=0):
1934 if self.closed:
1935 raise ValueError("tell on closed file")
1936 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001937 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001938 if whence == 1: # seek relative to current position
1939 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001940 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001941 # Seeking to the current position should attempt to
1942 # sync the underlying buffer with the current position.
1943 whence = 0
1944 cookie = self.tell()
1945 if whence == 2: # seek relative to end of file
1946 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001947 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001948 self.flush()
1949 position = self.buffer.seek(0, 2)
1950 self._set_decoded_chars('')
1951 self._snapshot = None
1952 if self._decoder:
1953 self._decoder.reset()
1954 return position
1955 if whence != 0:
Jesus Cea94363612012-06-22 18:32:07 +02001956 raise ValueError("unsupported whence (%r)" % (whence,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001957 if cookie < 0:
1958 raise ValueError("negative seek position %r" % (cookie,))
1959 self.flush()
1960
1961 # The strategy of seek() is to go back to the safe start point
1962 # and replay the effect of read(chars_to_skip) from there.
1963 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1964 self._unpack_cookie(cookie)
1965
1966 # Seek back to the safe start point.
1967 self.buffer.seek(start_pos)
1968 self._set_decoded_chars('')
1969 self._snapshot = None
1970
1971 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001972 if cookie == 0 and self._decoder:
1973 self._decoder.reset()
1974 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001975 self._decoder = self._decoder or self._get_decoder()
1976 self._decoder.setstate((b'', dec_flags))
1977 self._snapshot = (dec_flags, b'')
1978
1979 if chars_to_skip:
1980 # Just like _read_chunk, feed the decoder and save a snapshot.
1981 input_chunk = self.buffer.read(bytes_to_feed)
1982 self._set_decoded_chars(
1983 self._decoder.decode(input_chunk, need_eof))
1984 self._snapshot = (dec_flags, input_chunk)
1985
1986 # Skip chars_to_skip of the decoded characters.
1987 if len(self._decoded_chars) < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001988 raise OSError("can't restore logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001989 self._decoded_chars_used = chars_to_skip
1990
Antoine Pitroue4501852009-05-14 18:55:55 +00001991 # Finally, reset the encoder (merely useful for proper BOM handling)
1992 try:
1993 encoder = self._encoder or self._get_encoder()
1994 except LookupError:
1995 # Sometimes the encoder doesn't exist
1996 pass
1997 else:
1998 if cookie != 0:
1999 encoder.setstate(0)
2000 else:
2001 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002002 return cookie
2003
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002004 def read(self, size=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00002005 self._checkReadable()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002006 if size is None:
2007 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002008 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00002009 try:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002010 size.__index__
Florent Xiclunab14930c2010-03-13 15:26:44 +00002011 except AttributeError as err:
2012 raise TypeError("an integer is required") from err
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002013 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002014 # Read everything.
2015 result = (self._get_decoded_chars() +
2016 decoder.decode(self.buffer.read(), final=True))
2017 self._set_decoded_chars('')
2018 self._snapshot = None
2019 return result
2020 else:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002021 # Keep reading chunks until we have size characters to return.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002022 eof = False
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002023 result = self._get_decoded_chars(size)
2024 while len(result) < size and not eof:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002025 eof = not self._read_chunk()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002026 result += self._get_decoded_chars(size - len(result))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002027 return result
2028
2029 def __next__(self):
2030 self._telling = False
2031 line = self.readline()
2032 if not line:
2033 self._snapshot = None
2034 self._telling = self._seekable
2035 raise StopIteration
2036 return line
2037
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002038 def readline(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002039 if self.closed:
2040 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002041 if size is None:
2042 size = -1
2043 elif not isinstance(size, int):
2044 raise TypeError("size must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002045
2046 # Grab all the decoded text (we will rewind any extra bits later).
2047 line = self._get_decoded_chars()
2048
2049 start = 0
2050 # Make the decoder if it doesn't already exist.
2051 if not self._decoder:
2052 self._get_decoder()
2053
2054 pos = endpos = None
2055 while True:
2056 if self._readtranslate:
2057 # Newlines are already translated, only search for \n
2058 pos = line.find('\n', start)
2059 if pos >= 0:
2060 endpos = pos + 1
2061 break
2062 else:
2063 start = len(line)
2064
2065 elif self._readuniversal:
2066 # Universal newline search. Find any of \r, \r\n, \n
2067 # The decoder ensures that \r\n are not split in two pieces
2068
2069 # In C we'd look for these in parallel of course.
2070 nlpos = line.find("\n", start)
2071 crpos = line.find("\r", start)
2072 if crpos == -1:
2073 if nlpos == -1:
2074 # Nothing found
2075 start = len(line)
2076 else:
2077 # Found \n
2078 endpos = nlpos + 1
2079 break
2080 elif nlpos == -1:
2081 # Found lone \r
2082 endpos = crpos + 1
2083 break
2084 elif nlpos < crpos:
2085 # Found \n
2086 endpos = nlpos + 1
2087 break
2088 elif nlpos == crpos + 1:
2089 # Found \r\n
2090 endpos = crpos + 2
2091 break
2092 else:
2093 # Found \r
2094 endpos = crpos + 1
2095 break
2096 else:
2097 # non-universal
2098 pos = line.find(self._readnl)
2099 if pos >= 0:
2100 endpos = pos + len(self._readnl)
2101 break
2102
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002103 if size >= 0 and len(line) >= size:
2104 endpos = size # reached length size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002105 break
2106
2107 # No line ending seen yet - get more data'
2108 while self._read_chunk():
2109 if self._decoded_chars:
2110 break
2111 if self._decoded_chars:
2112 line += self._get_decoded_chars()
2113 else:
2114 # end of file
2115 self._set_decoded_chars('')
2116 self._snapshot = None
2117 return line
2118
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002119 if size >= 0 and endpos > size:
2120 endpos = size # don't exceed size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002121
2122 # Rewind _decoded_chars to just after the line ending we found.
2123 self._rewind_decoded_chars(len(line) - endpos)
2124 return line[:endpos]
2125
2126 @property
2127 def newlines(self):
2128 return self._decoder.newlines if self._decoder else None
2129
2130
2131class StringIO(TextIOWrapper):
2132 """Text I/O implementation using an in-memory buffer.
2133
2134 The initial_value argument sets the value of object. The newline
2135 argument is like the one of TextIOWrapper's constructor.
2136 """
2137
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002138 def __init__(self, initial_value="", newline="\n"):
2139 super(StringIO, self).__init__(BytesIO(),
2140 encoding="utf-8",
Serhiy Storchakac92ea762014-01-29 11:33:26 +02002141 errors="surrogatepass",
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002142 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002143 # Issue #5645: make universal newlines semantics the same as in the
2144 # C version, even under Windows.
2145 if newline is None:
2146 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002147 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002148 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002149 raise TypeError("initial_value must be str or None, not {0}"
2150 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002151 self.write(initial_value)
2152 self.seek(0)
2153
2154 def getvalue(self):
2155 self.flush()
Antoine Pitrou57839a62014-02-02 23:37:29 +01002156 decoder = self._decoder or self._get_decoder()
2157 old_state = decoder.getstate()
2158 decoder.reset()
2159 try:
2160 return decoder.decode(self.buffer.getvalue(), final=True)
2161 finally:
2162 decoder.setstate(old_state)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002163
2164 def __repr__(self):
2165 # TextIOWrapper tells the encoding in its repr. In StringIO,
2166 # that's a implementation detail.
2167 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002168
2169 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002170 def errors(self):
2171 return None
2172
2173 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002174 def encoding(self):
2175 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002176
2177 def detach(self):
2178 # This doesn't make sense on StringIO.
2179 self._unsupported("detach")