blob: f1611a48261c698f1e33de8ae72f7e3b9177c25e [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):
1294 self.writer.close()
1295 self.reader.close()
1296
1297 def isatty(self):
1298 return self.reader.isatty() or self.writer.isatty()
1299
1300 @property
1301 def closed(self):
1302 return self.writer.closed
1303
1304
1305class BufferedRandom(BufferedWriter, BufferedReader):
1306
1307 """A buffered interface to random access streams.
1308
1309 The constructor creates a reader and writer for a seekable stream,
1310 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001311 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001312 """
1313
Florent Xicluna109d5732012-07-07 17:03:22 +02001314 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001315 raw._checkSeekable()
1316 BufferedReader.__init__(self, raw, buffer_size)
Florent Xicluna109d5732012-07-07 17:03:22 +02001317 BufferedWriter.__init__(self, raw, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001318
1319 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001320 if whence not in valid_seek_flags:
1321 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001322 self.flush()
1323 if self._read_buf:
1324 # Undo read ahead.
1325 with self._read_lock:
1326 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1327 # First do the raw seek, then empty the read buffer, so that
1328 # if the raw seek fails, we don't lose buffered data forever.
1329 pos = self.raw.seek(pos, whence)
1330 with self._read_lock:
1331 self._reset_read_buf()
1332 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001333 raise OSError("seek() returned invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001334 return pos
1335
1336 def tell(self):
1337 if self._write_buf:
1338 return BufferedWriter.tell(self)
1339 else:
1340 return BufferedReader.tell(self)
1341
1342 def truncate(self, pos=None):
1343 if pos is None:
1344 pos = self.tell()
1345 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001346 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001347
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001348 def read(self, size=None):
1349 if size is None:
1350 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001351 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001352 return BufferedReader.read(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001353
1354 def readinto(self, b):
1355 self.flush()
1356 return BufferedReader.readinto(self, b)
1357
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001358 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001359 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001360 return BufferedReader.peek(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001361
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001362 def read1(self, size):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001363 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001364 return BufferedReader.read1(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001365
Benjamin Petersona96fea02014-06-22 14:17:44 -07001366 def readinto1(self, b):
1367 self.flush()
1368 return BufferedReader.readinto1(self, b)
1369
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001370 def write(self, b):
1371 if self._read_buf:
1372 # Undo readahead
1373 with self._read_lock:
1374 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1375 self._reset_read_buf()
1376 return BufferedWriter.write(self, b)
1377
1378
1379class TextIOBase(IOBase):
1380
1381 """Base class for text I/O.
1382
1383 This class provides a character and line based interface to stream
1384 I/O. There is no readinto method because Python's character strings
1385 are immutable. There is no public constructor.
1386 """
1387
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001388 def read(self, size=-1):
1389 """Read at most size characters from stream, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001390
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001391 Read from underlying buffer until we have size characters or we hit EOF.
1392 If size is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001393
1394 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001395 """
1396 self._unsupported("read")
1397
Raymond Hettinger3c940242011-01-12 23:39:31 +00001398 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001399 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001400 self._unsupported("write")
1401
Georg Brandl4d73b572011-01-13 07:13:06 +00001402 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001403 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001404 self._unsupported("truncate")
1405
Raymond Hettinger3c940242011-01-12 23:39:31 +00001406 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001407 """Read until newline or EOF.
1408
1409 Returns an empty string if EOF is hit immediately.
1410 """
1411 self._unsupported("readline")
1412
Raymond Hettinger3c940242011-01-12 23:39:31 +00001413 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001414 """
1415 Separate the underlying buffer from the TextIOBase and return it.
1416
1417 After the underlying buffer has been detached, the TextIO is in an
1418 unusable state.
1419 """
1420 self._unsupported("detach")
1421
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001422 @property
1423 def encoding(self):
1424 """Subclasses should override."""
1425 return None
1426
1427 @property
1428 def newlines(self):
1429 """Line endings translated so far.
1430
1431 Only line endings translated during reading are considered.
1432
1433 Subclasses should override.
1434 """
1435 return None
1436
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001437 @property
1438 def errors(self):
1439 """Error setting of the decoder or encoder.
1440
1441 Subclasses should override."""
1442 return None
1443
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001444io.TextIOBase.register(TextIOBase)
1445
1446
1447class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1448 r"""Codec used when reading a file in universal newlines mode. It wraps
1449 another incremental decoder, translating \r\n and \r into \n. It also
1450 records the types of newlines encountered. When used with
1451 translate=False, it ensures that the newline sequence is returned in
1452 one piece.
1453 """
1454 def __init__(self, decoder, translate, errors='strict'):
1455 codecs.IncrementalDecoder.__init__(self, errors=errors)
1456 self.translate = translate
1457 self.decoder = decoder
1458 self.seennl = 0
1459 self.pendingcr = False
1460
1461 def decode(self, input, final=False):
1462 # decode input (with the eventual \r from a previous pass)
1463 if self.decoder is None:
1464 output = input
1465 else:
1466 output = self.decoder.decode(input, final=final)
1467 if self.pendingcr and (output or final):
1468 output = "\r" + output
1469 self.pendingcr = False
1470
1471 # retain last \r even when not translating data:
1472 # then readline() is sure to get \r\n in one pass
1473 if output.endswith("\r") and not final:
1474 output = output[:-1]
1475 self.pendingcr = True
1476
1477 # Record which newlines are read
1478 crlf = output.count('\r\n')
1479 cr = output.count('\r') - crlf
1480 lf = output.count('\n') - crlf
1481 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1482 | (crlf and self._CRLF)
1483
1484 if self.translate:
1485 if crlf:
1486 output = output.replace("\r\n", "\n")
1487 if cr:
1488 output = output.replace("\r", "\n")
1489
1490 return output
1491
1492 def getstate(self):
1493 if self.decoder is None:
1494 buf = b""
1495 flag = 0
1496 else:
1497 buf, flag = self.decoder.getstate()
1498 flag <<= 1
1499 if self.pendingcr:
1500 flag |= 1
1501 return buf, flag
1502
1503 def setstate(self, state):
1504 buf, flag = state
1505 self.pendingcr = bool(flag & 1)
1506 if self.decoder is not None:
1507 self.decoder.setstate((buf, flag >> 1))
1508
1509 def reset(self):
1510 self.seennl = 0
1511 self.pendingcr = False
1512 if self.decoder is not None:
1513 self.decoder.reset()
1514
1515 _LF = 1
1516 _CR = 2
1517 _CRLF = 4
1518
1519 @property
1520 def newlines(self):
1521 return (None,
1522 "\n",
1523 "\r",
1524 ("\r", "\n"),
1525 "\r\n",
1526 ("\n", "\r\n"),
1527 ("\r", "\r\n"),
1528 ("\r", "\n", "\r\n")
1529 )[self.seennl]
1530
1531
1532class TextIOWrapper(TextIOBase):
1533
1534 r"""Character and line based layer over a BufferedIOBase object, buffer.
1535
1536 encoding gives the name of the encoding that the stream will be
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001537 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001538
1539 errors determines the strictness of encoding and decoding (see the
1540 codecs.register) and defaults to "strict".
1541
1542 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1543 handling of line endings. If it is None, universal newlines is
1544 enabled. With this enabled, on input, the lines endings '\n', '\r',
1545 or '\r\n' are translated to '\n' before being returned to the
1546 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001547 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001548 legal values, that newline becomes the newline when the file is read
1549 and it is returned untranslated. On output, '\n' is converted to the
1550 newline.
1551
1552 If line_buffering is True, a call to flush is implied when a call to
1553 write contains a newline character.
1554 """
1555
1556 _CHUNK_SIZE = 2048
1557
Andrew Svetlov4e9e9c12012-08-13 16:09:54 +03001558 # The write_through argument has no effect here since this
1559 # implementation always writes through. The argument is present only
1560 # so that the signature can match the signature of the C version.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001561 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001562 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001563 if newline is not None and not isinstance(newline, str):
1564 raise TypeError("illegal newline type: %r" % (type(newline),))
1565 if newline not in (None, "", "\n", "\r", "\r\n"):
1566 raise ValueError("illegal newline value: %r" % (newline,))
1567 if encoding is None:
1568 try:
1569 encoding = os.device_encoding(buffer.fileno())
1570 except (AttributeError, UnsupportedOperation):
1571 pass
1572 if encoding is None:
1573 try:
1574 import locale
Brett Cannoncd171c82013-07-04 17:43:24 -04001575 except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001576 # Importing locale may fail if Python is being built
1577 encoding = "ascii"
1578 else:
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001579 encoding = locale.getpreferredencoding(False)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001580
1581 if not isinstance(encoding, str):
1582 raise ValueError("invalid encoding: %r" % encoding)
1583
Nick Coghlana9b15242014-02-04 22:11:18 +10001584 if not codecs.lookup(encoding)._is_text_encoding:
1585 msg = ("%r is not a text encoding; "
1586 "use codecs.open() to handle arbitrary codecs")
1587 raise LookupError(msg % encoding)
1588
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001589 if errors is None:
1590 errors = "strict"
1591 else:
1592 if not isinstance(errors, str):
1593 raise ValueError("invalid errors: %r" % errors)
1594
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001595 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001596 self._line_buffering = line_buffering
1597 self._encoding = encoding
1598 self._errors = errors
1599 self._readuniversal = not newline
1600 self._readtranslate = newline is None
1601 self._readnl = newline
1602 self._writetranslate = newline != ''
1603 self._writenl = newline or os.linesep
1604 self._encoder = None
1605 self._decoder = None
1606 self._decoded_chars = '' # buffer for text returned from decoder
1607 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1608 self._snapshot = None # info for reconstructing decoder state
1609 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001610 self._has_read1 = hasattr(self.buffer, 'read1')
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001611 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001612
Antoine Pitroue4501852009-05-14 18:55:55 +00001613 if self._seekable and self.writable():
1614 position = self.buffer.tell()
1615 if position != 0:
1616 try:
1617 self._get_encoder().setstate(0)
1618 except LookupError:
1619 # Sometimes the encoder doesn't exist
1620 pass
1621
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001622 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1623 # where dec_flags is the second (integer) item of the decoder state
1624 # and next_input is the chunk of input bytes that comes next after the
1625 # snapshot point. We use this to reconstruct decoder states in tell().
1626
1627 # Naming convention:
1628 # - "bytes_..." for integer variables that count input bytes
1629 # - "chars_..." for integer variables that count decoded characters
1630
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001631 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +03001632 result = "<{}.{}".format(self.__class__.__module__,
1633 self.__class__.__qualname__)
Antoine Pitrou716c4442009-05-23 19:04:03 +00001634 try:
1635 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -06001636 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001637 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00001638 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001639 result += " name={0!r}".format(name)
1640 try:
1641 mode = self.mode
Benjamin Peterson10e76b62014-12-21 20:51:50 -06001642 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001643 pass
1644 else:
1645 result += " mode={0!r}".format(mode)
1646 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001647
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001648 @property
1649 def encoding(self):
1650 return self._encoding
1651
1652 @property
1653 def errors(self):
1654 return self._errors
1655
1656 @property
1657 def line_buffering(self):
1658 return self._line_buffering
1659
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001660 @property
1661 def buffer(self):
1662 return self._buffer
1663
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001664 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02001665 if self.closed:
1666 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001667 return self._seekable
1668
1669 def readable(self):
1670 return self.buffer.readable()
1671
1672 def writable(self):
1673 return self.buffer.writable()
1674
1675 def flush(self):
1676 self.buffer.flush()
1677 self._telling = self._seekable
1678
1679 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00001680 if self.buffer is not None and not self.closed:
Benjamin Peterson68623612012-12-20 11:53:11 -06001681 try:
1682 self.flush()
1683 finally:
1684 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001685
1686 @property
1687 def closed(self):
1688 return self.buffer.closed
1689
1690 @property
1691 def name(self):
1692 return self.buffer.name
1693
1694 def fileno(self):
1695 return self.buffer.fileno()
1696
1697 def isatty(self):
1698 return self.buffer.isatty()
1699
Raymond Hettinger00fa0392011-01-13 02:52:26 +00001700 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001701 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001702 if self.closed:
1703 raise ValueError("write to closed file")
1704 if not isinstance(s, str):
1705 raise TypeError("can't write %s to text stream" %
1706 s.__class__.__name__)
1707 length = len(s)
1708 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1709 if haslf and self._writetranslate and self._writenl != "\n":
1710 s = s.replace("\n", self._writenl)
1711 encoder = self._encoder or self._get_encoder()
1712 # XXX What if we were just reading?
1713 b = encoder.encode(s)
1714 self.buffer.write(b)
1715 if self._line_buffering and (haslf or "\r" in s):
1716 self.flush()
1717 self._snapshot = None
1718 if self._decoder:
1719 self._decoder.reset()
1720 return length
1721
1722 def _get_encoder(self):
1723 make_encoder = codecs.getincrementalencoder(self._encoding)
1724 self._encoder = make_encoder(self._errors)
1725 return self._encoder
1726
1727 def _get_decoder(self):
1728 make_decoder = codecs.getincrementaldecoder(self._encoding)
1729 decoder = make_decoder(self._errors)
1730 if self._readuniversal:
1731 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1732 self._decoder = decoder
1733 return decoder
1734
1735 # The following three methods implement an ADT for _decoded_chars.
1736 # Text returned from the decoder is buffered here until the client
1737 # requests it by calling our read() or readline() method.
1738 def _set_decoded_chars(self, chars):
1739 """Set the _decoded_chars buffer."""
1740 self._decoded_chars = chars
1741 self._decoded_chars_used = 0
1742
1743 def _get_decoded_chars(self, n=None):
1744 """Advance into the _decoded_chars buffer."""
1745 offset = self._decoded_chars_used
1746 if n is None:
1747 chars = self._decoded_chars[offset:]
1748 else:
1749 chars = self._decoded_chars[offset:offset + n]
1750 self._decoded_chars_used += len(chars)
1751 return chars
1752
1753 def _rewind_decoded_chars(self, n):
1754 """Rewind the _decoded_chars buffer."""
1755 if self._decoded_chars_used < n:
1756 raise AssertionError("rewind decoded_chars out of bounds")
1757 self._decoded_chars_used -= n
1758
1759 def _read_chunk(self):
1760 """
1761 Read and decode the next chunk of data from the BufferedReader.
1762 """
1763
1764 # The return value is True unless EOF was reached. The decoded
1765 # string is placed in self._decoded_chars (replacing its previous
1766 # value). The entire input chunk is sent to the decoder, though
1767 # some of it may remain buffered in the decoder, yet to be
1768 # converted.
1769
1770 if self._decoder is None:
1771 raise ValueError("no decoder")
1772
1773 if self._telling:
1774 # To prepare for tell(), we need to snapshot a point in the
1775 # file where the decoder's input buffer is empty.
1776
1777 dec_buffer, dec_flags = self._decoder.getstate()
1778 # Given this, we know there was a valid snapshot point
1779 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1780
1781 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02001782 if self._has_read1:
1783 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1784 else:
1785 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001786 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001787 decoded_chars = self._decoder.decode(input_chunk, eof)
1788 self._set_decoded_chars(decoded_chars)
1789 if decoded_chars:
1790 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
1791 else:
1792 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001793
1794 if self._telling:
1795 # At the snapshot point, len(dec_buffer) bytes before the read,
1796 # the next input to be decoded is dec_buffer + input_chunk.
1797 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1798
1799 return not eof
1800
1801 def _pack_cookie(self, position, dec_flags=0,
1802 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1803 # The meaning of a tell() cookie is: seek to position, set the
1804 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1805 # into the decoder with need_eof as the EOF flag, then skip
1806 # chars_to_skip characters of the decoded result. For most simple
1807 # decoders, tell() will often just give a byte offset in the file.
1808 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1809 (chars_to_skip<<192) | bool(need_eof)<<256)
1810
1811 def _unpack_cookie(self, bigint):
1812 rest, position = divmod(bigint, 1<<64)
1813 rest, dec_flags = divmod(rest, 1<<64)
1814 rest, bytes_to_feed = divmod(rest, 1<<64)
1815 need_eof, chars_to_skip = divmod(rest, 1<<64)
1816 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1817
1818 def tell(self):
1819 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001820 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001821 if not self._telling:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001822 raise OSError("telling position disabled by next() call")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001823 self.flush()
1824 position = self.buffer.tell()
1825 decoder = self._decoder
1826 if decoder is None or self._snapshot is None:
1827 if self._decoded_chars:
1828 # This should never happen.
1829 raise AssertionError("pending decoded text")
1830 return position
1831
1832 # Skip backward to the snapshot point (see _read_chunk).
1833 dec_flags, next_input = self._snapshot
1834 position -= len(next_input)
1835
1836 # How many decoded characters have been used up since the snapshot?
1837 chars_to_skip = self._decoded_chars_used
1838 if chars_to_skip == 0:
1839 # We haven't moved from the snapshot point.
1840 return self._pack_cookie(position, dec_flags)
1841
1842 # Starting from the snapshot position, we will walk the decoder
1843 # forward until it gives us enough decoded characters.
1844 saved_state = decoder.getstate()
1845 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001846 # Fast search for an acceptable start point, close to our
1847 # current pos.
1848 # Rationale: calling decoder.decode() has a large overhead
1849 # regardless of chunk size; we want the number of such calls to
1850 # be O(1) in most situations (common decoders, non-crazy input).
1851 # Actually, it will be exactly 1 for fixed-size codecs (all
1852 # 8-bit codecs, also UTF-16 and UTF-32).
1853 skip_bytes = int(self._b2cratio * chars_to_skip)
1854 skip_back = 1
1855 assert skip_bytes <= len(next_input)
1856 while skip_bytes > 0:
1857 decoder.setstate((b'', dec_flags))
1858 # Decode up to temptative start point
1859 n = len(decoder.decode(next_input[:skip_bytes]))
1860 if n <= chars_to_skip:
1861 b, d = decoder.getstate()
1862 if not b:
1863 # Before pos and no bytes buffered in decoder => OK
1864 dec_flags = d
1865 chars_to_skip -= n
1866 break
1867 # Skip back by buffered amount and reset heuristic
1868 skip_bytes -= len(b)
1869 skip_back = 1
1870 else:
1871 # We're too far ahead, skip back a bit
1872 skip_bytes -= skip_back
1873 skip_back = skip_back * 2
1874 else:
1875 skip_bytes = 0
1876 decoder.setstate((b'', dec_flags))
1877
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001878 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001879 start_pos = position + skip_bytes
1880 start_flags = dec_flags
1881 if chars_to_skip == 0:
1882 # We haven't moved from the start point.
1883 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001884
1885 # Feed the decoder one byte at a time. As we go, note the
1886 # nearest "safe start point" before the current location
1887 # (a point where the decoder has nothing buffered, so seek()
1888 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001889 bytes_fed = 0
1890 need_eof = 0
1891 # Chars decoded since `start_pos`
1892 chars_decoded = 0
1893 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001894 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001895 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001896 dec_buffer, dec_flags = decoder.getstate()
1897 if not dec_buffer and chars_decoded <= chars_to_skip:
1898 # Decoder buffer is empty, so this is a safe start point.
1899 start_pos += bytes_fed
1900 chars_to_skip -= chars_decoded
1901 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1902 if chars_decoded >= chars_to_skip:
1903 break
1904 else:
1905 # We didn't get enough decoded data; signal EOF to get more.
1906 chars_decoded += len(decoder.decode(b'', final=True))
1907 need_eof = 1
1908 if chars_decoded < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001909 raise OSError("can't reconstruct logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001910
1911 # The returned cookie corresponds to the last safe start point.
1912 return self._pack_cookie(
1913 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1914 finally:
1915 decoder.setstate(saved_state)
1916
1917 def truncate(self, pos=None):
1918 self.flush()
1919 if pos is None:
1920 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001921 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001922
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001923 def detach(self):
1924 if self.buffer is None:
1925 raise ValueError("buffer is already detached")
1926 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001927 buffer = self._buffer
1928 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001929 return buffer
1930
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001931 def seek(self, cookie, whence=0):
1932 if self.closed:
1933 raise ValueError("tell on closed file")
1934 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001935 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001936 if whence == 1: # seek relative to current position
1937 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001938 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001939 # Seeking to the current position should attempt to
1940 # sync the underlying buffer with the current position.
1941 whence = 0
1942 cookie = self.tell()
1943 if whence == 2: # seek relative to end of file
1944 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001945 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001946 self.flush()
1947 position = self.buffer.seek(0, 2)
1948 self._set_decoded_chars('')
1949 self._snapshot = None
1950 if self._decoder:
1951 self._decoder.reset()
1952 return position
1953 if whence != 0:
Jesus Cea94363612012-06-22 18:32:07 +02001954 raise ValueError("unsupported whence (%r)" % (whence,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001955 if cookie < 0:
1956 raise ValueError("negative seek position %r" % (cookie,))
1957 self.flush()
1958
1959 # The strategy of seek() is to go back to the safe start point
1960 # and replay the effect of read(chars_to_skip) from there.
1961 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1962 self._unpack_cookie(cookie)
1963
1964 # Seek back to the safe start point.
1965 self.buffer.seek(start_pos)
1966 self._set_decoded_chars('')
1967 self._snapshot = None
1968
1969 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001970 if cookie == 0 and self._decoder:
1971 self._decoder.reset()
1972 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001973 self._decoder = self._decoder or self._get_decoder()
1974 self._decoder.setstate((b'', dec_flags))
1975 self._snapshot = (dec_flags, b'')
1976
1977 if chars_to_skip:
1978 # Just like _read_chunk, feed the decoder and save a snapshot.
1979 input_chunk = self.buffer.read(bytes_to_feed)
1980 self._set_decoded_chars(
1981 self._decoder.decode(input_chunk, need_eof))
1982 self._snapshot = (dec_flags, input_chunk)
1983
1984 # Skip chars_to_skip of the decoded characters.
1985 if len(self._decoded_chars) < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001986 raise OSError("can't restore logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001987 self._decoded_chars_used = chars_to_skip
1988
Antoine Pitroue4501852009-05-14 18:55:55 +00001989 # Finally, reset the encoder (merely useful for proper BOM handling)
1990 try:
1991 encoder = self._encoder or self._get_encoder()
1992 except LookupError:
1993 # Sometimes the encoder doesn't exist
1994 pass
1995 else:
1996 if cookie != 0:
1997 encoder.setstate(0)
1998 else:
1999 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002000 return cookie
2001
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002002 def read(self, size=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00002003 self._checkReadable()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002004 if size is None:
2005 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002006 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00002007 try:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002008 size.__index__
Florent Xiclunab14930c2010-03-13 15:26:44 +00002009 except AttributeError as err:
2010 raise TypeError("an integer is required") from err
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002011 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002012 # Read everything.
2013 result = (self._get_decoded_chars() +
2014 decoder.decode(self.buffer.read(), final=True))
2015 self._set_decoded_chars('')
2016 self._snapshot = None
2017 return result
2018 else:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002019 # Keep reading chunks until we have size characters to return.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002020 eof = False
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002021 result = self._get_decoded_chars(size)
2022 while len(result) < size and not eof:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002023 eof = not self._read_chunk()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002024 result += self._get_decoded_chars(size - len(result))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002025 return result
2026
2027 def __next__(self):
2028 self._telling = False
2029 line = self.readline()
2030 if not line:
2031 self._snapshot = None
2032 self._telling = self._seekable
2033 raise StopIteration
2034 return line
2035
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002036 def readline(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002037 if self.closed:
2038 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002039 if size is None:
2040 size = -1
2041 elif not isinstance(size, int):
2042 raise TypeError("size must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002043
2044 # Grab all the decoded text (we will rewind any extra bits later).
2045 line = self._get_decoded_chars()
2046
2047 start = 0
2048 # Make the decoder if it doesn't already exist.
2049 if not self._decoder:
2050 self._get_decoder()
2051
2052 pos = endpos = None
2053 while True:
2054 if self._readtranslate:
2055 # Newlines are already translated, only search for \n
2056 pos = line.find('\n', start)
2057 if pos >= 0:
2058 endpos = pos + 1
2059 break
2060 else:
2061 start = len(line)
2062
2063 elif self._readuniversal:
2064 # Universal newline search. Find any of \r, \r\n, \n
2065 # The decoder ensures that \r\n are not split in two pieces
2066
2067 # In C we'd look for these in parallel of course.
2068 nlpos = line.find("\n", start)
2069 crpos = line.find("\r", start)
2070 if crpos == -1:
2071 if nlpos == -1:
2072 # Nothing found
2073 start = len(line)
2074 else:
2075 # Found \n
2076 endpos = nlpos + 1
2077 break
2078 elif nlpos == -1:
2079 # Found lone \r
2080 endpos = crpos + 1
2081 break
2082 elif nlpos < crpos:
2083 # Found \n
2084 endpos = nlpos + 1
2085 break
2086 elif nlpos == crpos + 1:
2087 # Found \r\n
2088 endpos = crpos + 2
2089 break
2090 else:
2091 # Found \r
2092 endpos = crpos + 1
2093 break
2094 else:
2095 # non-universal
2096 pos = line.find(self._readnl)
2097 if pos >= 0:
2098 endpos = pos + len(self._readnl)
2099 break
2100
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002101 if size >= 0 and len(line) >= size:
2102 endpos = size # reached length size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002103 break
2104
2105 # No line ending seen yet - get more data'
2106 while self._read_chunk():
2107 if self._decoded_chars:
2108 break
2109 if self._decoded_chars:
2110 line += self._get_decoded_chars()
2111 else:
2112 # end of file
2113 self._set_decoded_chars('')
2114 self._snapshot = None
2115 return line
2116
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002117 if size >= 0 and endpos > size:
2118 endpos = size # don't exceed size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002119
2120 # Rewind _decoded_chars to just after the line ending we found.
2121 self._rewind_decoded_chars(len(line) - endpos)
2122 return line[:endpos]
2123
2124 @property
2125 def newlines(self):
2126 return self._decoder.newlines if self._decoder else None
2127
2128
2129class StringIO(TextIOWrapper):
2130 """Text I/O implementation using an in-memory buffer.
2131
2132 The initial_value argument sets the value of object. The newline
2133 argument is like the one of TextIOWrapper's constructor.
2134 """
2135
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002136 def __init__(self, initial_value="", newline="\n"):
2137 super(StringIO, self).__init__(BytesIO(),
2138 encoding="utf-8",
Serhiy Storchakac92ea762014-01-29 11:33:26 +02002139 errors="surrogatepass",
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002140 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002141 # Issue #5645: make universal newlines semantics the same as in the
2142 # C version, even under Windows.
2143 if newline is None:
2144 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002145 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002146 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002147 raise TypeError("initial_value must be str or None, not {0}"
2148 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002149 self.write(initial_value)
2150 self.seek(0)
2151
2152 def getvalue(self):
2153 self.flush()
Antoine Pitrou57839a62014-02-02 23:37:29 +01002154 decoder = self._decoder or self._get_decoder()
2155 old_state = decoder.getstate()
2156 decoder.reset()
2157 try:
2158 return decoder.decode(self.buffer.getvalue(), final=True)
2159 finally:
2160 decoder.setstate(old_state)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002161
2162 def __repr__(self):
2163 # TextIOWrapper tells the encoding in its repr. In StringIO,
2164 # that's a implementation detail.
2165 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002166
2167 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002168 def errors(self):
2169 return None
2170
2171 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002172 def encoding(self):
2173 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002174
2175 def detach(self):
2176 # This doesn't make sense on StringIO.
2177 self._unsupported("detach")