blob: 09aa78decd2e0b309d73299192d4b9dd067e8fb3 [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 Peterson4fa88fa2009-03-04 00:14:51 +00009# Import _thread instead of threading to reduce startup cost
10try:
11 from _thread import allocate_lock as Lock
Brett Cannoncd171c82013-07-04 17:43:24 -040012except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000013 from _dummy_thread import allocate_lock as Lock
14
15import io
Benjamin Petersonc3be11a2010-04-27 21:24:03 +000016from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000017
Jesus Cea94363612012-06-22 18:32:07 +020018valid_seek_flags = {0, 1, 2} # Hardwired values
19if hasattr(os, 'SEEK_HOLE') :
20 valid_seek_flags.add(os.SEEK_HOLE)
21 valid_seek_flags.add(os.SEEK_DATA)
22
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000023# open() uses st_blksize whenever we can
24DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
25
26# NOTE: Base classes defined here are registered with the "official" ABCs
Benjamin Peterson86fdbf32015-03-18 21:35:38 -050027# defined in io.py. We don't use real inheritance though, because we don't want
28# to inherit the C implementations.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000029
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020030# Rebind for compatibility
31BlockingIOError = BlockingIOError
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000032
33
Georg Brandl4d73b572011-01-13 07:13:06 +000034def open(file, mode="r", buffering=-1, encoding=None, errors=None,
Ross Lagerwall59142db2011-10-31 20:34:46 +020035 newline=None, closefd=True, opener=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000036
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020037 r"""Open file and return a stream. Raise OSError upon failure.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000038
39 file is either a text or byte string giving the name (and the path
40 if the file isn't in the current working directory) of the file to
41 be opened or an integer file descriptor of the file to be
42 wrapped. (If a file descriptor is given, it is closed when the
43 returned I/O object is closed, unless closefd is set to False.)
44
Charles-François Natalidc3044c2012-01-09 22:40:02 +010045 mode is an optional string that specifies the mode in which the file is
46 opened. It defaults to 'r' which means open for reading in text mode. Other
47 common values are 'w' for writing (truncating the file if it already
Charles-François Natalid612de12012-01-14 11:51:00 +010048 exists), 'x' for exclusive creation of a new file, and 'a' for appending
Charles-François Natalidc3044c2012-01-09 22:40:02 +010049 (which on some Unix systems, means that all writes append to the end of the
50 file regardless of the current seek position). In text mode, if encoding is
51 not specified the encoding used is platform dependent. (For reading and
52 writing raw bytes use binary mode and leave encoding unspecified.) The
53 available modes are:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000054
55 ========= ===============================================================
56 Character Meaning
57 --------- ---------------------------------------------------------------
58 'r' open for reading (default)
59 'w' open for writing, truncating the file first
Charles-François Natalidc3044c2012-01-09 22:40:02 +010060 'x' create a new file and open it for writing
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000061 'a' open for writing, appending to the end of the file if it exists
62 'b' binary mode
63 't' text mode (default)
64 '+' open a disk file for updating (reading and writing)
Serhiy Storchaka6787a382013-11-23 22:12:06 +020065 'U' universal newline mode (deprecated)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000066 ========= ===============================================================
67
68 The default mode is 'rt' (open for reading text). For binary random
69 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
Charles-François Natalidc3044c2012-01-09 22:40:02 +010070 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
71 raises an `FileExistsError` if the file already exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000072
73 Python distinguishes between files opened in binary and text modes,
74 even when the underlying operating system doesn't. Files opened in
75 binary mode (appending 'b' to the mode argument) return contents as
76 bytes objects without any decoding. In text mode (the default, or when
77 't' is appended to the mode argument), the contents of the file are
78 returned as strings, the bytes having been first decoded using a
79 platform-dependent encoding or using the specified encoding if given.
80
Serhiy Storchaka6787a382013-11-23 22:12:06 +020081 'U' mode is deprecated and will raise an exception in future versions
82 of Python. It has no effect in Python 3. Use newline to control
83 universal newlines mode.
84
Antoine Pitroud5587bc2009-12-19 21:08:31 +000085 buffering is an optional integer used to set the buffering policy.
86 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
87 line buffering (only usable in text mode), and an integer > 1 to indicate
88 the size of a fixed-size chunk buffer. When no buffering argument is
89 given, the default buffering policy works as follows:
90
91 * Binary files are buffered in fixed-size chunks; the size of the buffer
92 is chosen using a heuristic trying to determine the underlying device's
93 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
94 On many systems, the buffer will typically be 4096 or 8192 bytes long.
95
96 * "Interactive" text files (files for which isatty() returns True)
97 use line buffering. Other text files use the policy described above
98 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000099
Raymond Hettingercbb80892011-01-13 18:15:51 +0000100 encoding is the str name of the encoding used to decode or encode the
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000101 file. This should only be used in text mode. The default encoding is
102 platform dependent, but any encoding supported by Python can be
103 passed. See the codecs module for the list of supported encodings.
104
105 errors is an optional string that specifies how encoding errors are to
106 be handled---this argument should not be used in binary mode. Pass
107 'strict' to raise a ValueError exception if there is an encoding error
108 (the default of None has the same effect), or pass 'ignore' to ignore
109 errors. (Note that ignoring encoding errors can lead to data loss.)
110 See the documentation for codecs.register for a list of the permitted
111 encoding error strings.
112
Raymond Hettingercbb80892011-01-13 18:15:51 +0000113 newline is a string controlling how universal newlines works (it only
114 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
115 as follows:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000116
117 * On input, if newline is None, universal newlines mode is
118 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
119 these are translated into '\n' before being returned to the
120 caller. If it is '', universal newline mode is enabled, but line
121 endings are returned to the caller untranslated. If it has any of
122 the other legal values, input lines are only terminated by the given
123 string, and the line ending is returned to the caller untranslated.
124
125 * On output, if newline is None, any '\n' characters written are
126 translated to the system default line separator, os.linesep. If
127 newline is '', no translation takes place. If newline is any of the
128 other legal values, any '\n' characters written are translated to
129 the given string.
130
Raymond Hettingercbb80892011-01-13 18:15:51 +0000131 closedfd is a bool. If closefd is False, the underlying file descriptor will
132 be kept open when the file is closed. This does not work when a file name is
133 given and must be True in that case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000134
Victor Stinnerdaf45552013-08-28 00:53:59 +0200135 The newly created file is non-inheritable.
136
Ross Lagerwall59142db2011-10-31 20:34:46 +0200137 A custom opener can be used by passing a callable as *opener*. The
138 underlying file descriptor for the file object is then obtained by calling
139 *opener* with (*file*, *flags*). *opener* must return an open file
140 descriptor (passing os.open as *opener* results in functionality similar to
141 passing None).
142
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000143 open() returns a file object whose type depends on the mode, and
144 through which the standard file operations such as reading and writing
145 are performed. When open() is used to open a file in a text mode ('w',
146 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
147 a file in a binary mode, the returned class varies: in read binary
148 mode, it returns a BufferedReader; in write binary and append binary
149 modes, it returns a BufferedWriter, and in read/write mode, it returns
150 a BufferedRandom.
151
152 It is also possible to use a string or bytearray as a file for both
153 reading and writing. For strings StringIO can be used like a file
154 opened in a text mode, and for bytes a BytesIO can be used like a file
155 opened in a binary mode.
156 """
157 if not isinstance(file, (str, bytes, int)):
158 raise TypeError("invalid file: %r" % file)
159 if not isinstance(mode, str):
160 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000161 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000162 raise TypeError("invalid buffering: %r" % buffering)
163 if encoding is not None and not isinstance(encoding, str):
164 raise TypeError("invalid encoding: %r" % encoding)
165 if errors is not None and not isinstance(errors, str):
166 raise TypeError("invalid errors: %r" % errors)
167 modes = set(mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100168 if modes - set("axrwb+tU") or len(mode) > len(modes):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000169 raise ValueError("invalid mode: %r" % mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100170 creating = "x" in modes
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000171 reading = "r" in modes
172 writing = "w" in modes
173 appending = "a" in modes
174 updating = "+" in modes
175 text = "t" in modes
176 binary = "b" in modes
177 if "U" in modes:
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100178 if creating or writing or appending:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000179 raise ValueError("can't use U and writing mode at once")
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200180 import warnings
181 warnings.warn("'U' mode is deprecated",
182 DeprecationWarning, 2)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000183 reading = True
184 if text and binary:
185 raise ValueError("can't have text and binary mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100186 if creating + reading + writing + appending > 1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000187 raise ValueError("can't have read/write/append mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100188 if not (creating or reading or writing or appending):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000189 raise ValueError("must have exactly one of read/write/append mode")
190 if binary and encoding is not None:
191 raise ValueError("binary mode doesn't take an encoding argument")
192 if binary and errors is not None:
193 raise ValueError("binary mode doesn't take an errors argument")
194 if binary and newline is not None:
195 raise ValueError("binary mode doesn't take a newline argument")
196 raw = FileIO(file,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100197 (creating and "x" or "") +
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000198 (reading and "r" or "") +
199 (writing and "w" or "") +
200 (appending and "a" or "") +
201 (updating and "+" or ""),
Ross Lagerwall59142db2011-10-31 20:34:46 +0200202 closefd, opener=opener)
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300203 result = raw
204 try:
205 line_buffering = False
206 if buffering == 1 or buffering < 0 and raw.isatty():
207 buffering = -1
208 line_buffering = True
209 if buffering < 0:
210 buffering = DEFAULT_BUFFER_SIZE
211 try:
212 bs = os.fstat(raw.fileno()).st_blksize
213 except (OSError, AttributeError):
214 pass
215 else:
216 if bs > 1:
217 buffering = bs
218 if buffering < 0:
219 raise ValueError("invalid buffering size")
220 if buffering == 0:
221 if binary:
222 return result
223 raise ValueError("can't have unbuffered text I/O")
224 if updating:
225 buffer = BufferedRandom(raw, buffering)
226 elif creating or writing or appending:
227 buffer = BufferedWriter(raw, buffering)
228 elif reading:
229 buffer = BufferedReader(raw, buffering)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000230 else:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300231 raise ValueError("unknown mode: %r" % mode)
232 result = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000233 if binary:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300234 return result
235 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
236 result = text
237 text.mode = mode
238 return result
239 except:
240 result.close()
241 raise
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000242
243
244class DocDescriptor:
245 """Helper for builtins.open.__doc__
246 """
247 def __get__(self, obj, typ):
248 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000249 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000250 "errors=None, newline=None, closefd=True)\n\n" +
251 open.__doc__)
252
253class OpenWrapper:
254 """Wrapper for builtins.open
255
256 Trick so that open won't become a bound method when stored
257 as a class variable (as dbm.dumb does).
258
259 See initstdio() in Python/pythonrun.c.
260 """
261 __doc__ = DocDescriptor()
262
263 def __new__(cls, *args, **kwargs):
264 return open(*args, **kwargs)
265
266
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000267# In normal operation, both `UnsupportedOperation`s should be bound to the
268# same object.
269try:
270 UnsupportedOperation = io.UnsupportedOperation
271except AttributeError:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200272 class UnsupportedOperation(ValueError, OSError):
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000273 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000274
275
276class IOBase(metaclass=abc.ABCMeta):
277
278 """The abstract base class for all I/O classes, acting on streams of
279 bytes. There is no public constructor.
280
281 This class provides dummy implementations for many methods that
282 derived classes can override selectively; the default implementations
283 represent a file that cannot be read, written or seeked.
284
285 Even though IOBase does not declare read, readinto, or write because
286 their signatures will vary, implementations and clients should
287 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000288 may raise UnsupportedOperation when operations they do not support are
289 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000290
291 The basic type used for binary data read from or written to a file is
292 bytes. bytearrays are accepted too, and in some cases (such as
293 readinto) needed. Text I/O classes work with str data.
294
295 Note that calling any method (even inquiries) on a closed stream is
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200296 undefined. Implementations may raise OSError in this case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000297
298 IOBase (and its subclasses) support the iterator protocol, meaning
299 that an IOBase object can be iterated over yielding the lines in a
300 stream.
301
302 IOBase also supports the :keyword:`with` statement. In this example,
303 fp is closed after the suite of the with statement is complete:
304
305 with open('spam.txt', 'r') as fp:
306 fp.write('Spam and eggs!')
307 """
308
309 ### Internal ###
310
Raymond Hettinger3c940242011-01-12 23:39:31 +0000311 def _unsupported(self, name):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200312 """Internal: raise an OSError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000313 raise UnsupportedOperation("%s.%s() not supported" %
314 (self.__class__.__name__, name))
315
316 ### Positioning ###
317
Georg Brandl4d73b572011-01-13 07:13:06 +0000318 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000319 """Change stream position.
320
Terry Jan Reedyc30b7b12013-03-11 17:57:08 -0400321 Change the stream position to byte offset pos. Argument pos is
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000322 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000323 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000324
325 * 0 -- start of stream (the default); offset should be zero or positive
326 * 1 -- current stream position; offset may be negative
327 * 2 -- end of stream; offset is usually negative
Jesus Cea94363612012-06-22 18:32:07 +0200328 Some operating systems / file systems could provide additional values.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000329
Raymond Hettingercbb80892011-01-13 18:15:51 +0000330 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000331 """
332 self._unsupported("seek")
333
Raymond Hettinger3c940242011-01-12 23:39:31 +0000334 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000335 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000336 return self.seek(0, 1)
337
Georg Brandl4d73b572011-01-13 07:13:06 +0000338 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000339 """Truncate file to size bytes.
340
341 Size defaults to the current IO position as reported by tell(). Return
342 the new size.
343 """
344 self._unsupported("truncate")
345
346 ### Flush and close ###
347
Raymond Hettinger3c940242011-01-12 23:39:31 +0000348 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000349 """Flush write buffers, if applicable.
350
351 This is not implemented for read-only and non-blocking streams.
352 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000353 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000354 # XXX Should this return the number of bytes written???
355
356 __closed = False
357
Raymond Hettinger3c940242011-01-12 23:39:31 +0000358 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000359 """Flush and close the IO object.
360
361 This method has no effect if the file is already closed.
362 """
363 if not self.__closed:
Benjamin Peterson68623612012-12-20 11:53:11 -0600364 try:
365 self.flush()
366 finally:
367 self.__closed = True
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000368
Raymond Hettinger3c940242011-01-12 23:39:31 +0000369 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000370 """Destructor. Calls close()."""
371 # The try/except block is in case this is called at program
372 # exit time, when it's possible that globals have already been
373 # deleted, and then the close() call might fail. Since
374 # there's nothing we can do about such failures and they annoy
375 # the end users, we suppress the traceback.
376 try:
377 self.close()
378 except:
379 pass
380
381 ### Inquiries ###
382
Raymond Hettinger3c940242011-01-12 23:39:31 +0000383 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000384 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000385
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000386 If False, seek(), tell() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000387 This method may need to do a test seek().
388 """
389 return False
390
391 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000392 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000393 """
394 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000395 raise UnsupportedOperation("File or stream is not seekable."
396 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000397
Raymond Hettinger3c940242011-01-12 23:39:31 +0000398 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000399 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000400
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000401 If False, read() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000402 """
403 return False
404
405 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000406 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000407 """
408 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000409 raise UnsupportedOperation("File or stream is not readable."
410 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000411
Raymond Hettinger3c940242011-01-12 23:39:31 +0000412 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000413 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000414
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000415 If False, write() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000416 """
417 return False
418
419 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000420 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000421 """
422 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000423 raise UnsupportedOperation("File or stream is not writable."
424 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000425
426 @property
427 def closed(self):
428 """closed: bool. True iff the file has been closed.
429
430 For backwards compatibility, this is a property, not a predicate.
431 """
432 return self.__closed
433
434 def _checkClosed(self, msg=None):
435 """Internal: raise an ValueError if file is closed
436 """
437 if self.closed:
438 raise ValueError("I/O operation on closed file."
439 if msg is None else msg)
440
441 ### Context manager ###
442
Raymond Hettinger3c940242011-01-12 23:39:31 +0000443 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000444 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000445 self._checkClosed()
446 return self
447
Raymond Hettinger3c940242011-01-12 23:39:31 +0000448 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000449 """Context management protocol. Calls close()"""
450 self.close()
451
452 ### Lower-level APIs ###
453
454 # XXX Should these be present even if unimplemented?
455
Raymond Hettinger3c940242011-01-12 23:39:31 +0000456 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000457 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000458
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200459 An OSError is raised if the IO object does not use a file descriptor.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000460 """
461 self._unsupported("fileno")
462
Raymond Hettinger3c940242011-01-12 23:39:31 +0000463 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000464 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000465
466 Return False if it can't be determined.
467 """
468 self._checkClosed()
469 return False
470
471 ### Readline[s] and writelines ###
472
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300473 def readline(self, size=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000474 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000475
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300476 If size is specified, at most size bytes will be read.
477 Size should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000478
479 The line terminator is always b'\n' for binary files; for text
480 files, the newlines argument to open can be used to select the line
481 terminator(s) recognized.
482 """
483 # For backwards compatibility, a (slowish) readline().
484 if hasattr(self, "peek"):
485 def nreadahead():
486 readahead = self.peek(1)
487 if not readahead:
488 return 1
489 n = (readahead.find(b"\n") + 1) or len(readahead)
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300490 if size >= 0:
491 n = min(n, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000492 return n
493 else:
494 def nreadahead():
495 return 1
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300496 if size is None:
497 size = -1
498 elif not isinstance(size, int):
499 raise TypeError("size must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000500 res = bytearray()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300501 while size < 0 or len(res) < size:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000502 b = self.read(nreadahead())
503 if not b:
504 break
505 res += b
506 if res.endswith(b"\n"):
507 break
508 return bytes(res)
509
510 def __iter__(self):
511 self._checkClosed()
512 return self
513
514 def __next__(self):
515 line = self.readline()
516 if not line:
517 raise StopIteration
518 return line
519
520 def readlines(self, hint=None):
521 """Return a list of lines from the stream.
522
523 hint can be specified to control the number of lines read: no more
524 lines will be read if the total size (in bytes/characters) of all
525 lines so far exceeds hint.
526 """
527 if hint is None or hint <= 0:
528 return list(self)
529 n = 0
530 lines = []
531 for line in self:
532 lines.append(line)
533 n += len(line)
534 if n >= hint:
535 break
536 return lines
537
538 def writelines(self, lines):
539 self._checkClosed()
540 for line in lines:
541 self.write(line)
542
543io.IOBase.register(IOBase)
544
545
546class RawIOBase(IOBase):
547
548 """Base class for raw binary I/O."""
549
550 # The read() method is implemented by calling readinto(); derived
551 # classes that want to support read() only need to implement
552 # readinto() as a primitive operation. In general, readinto() can be
553 # more efficient than read().
554
555 # (It would be tempting to also provide an implementation of
556 # readinto() in terms of read(), in case the latter is a more suitable
557 # primitive operation, but that would lead to nasty recursion in case
558 # a subclass doesn't implement either.)
559
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300560 def read(self, size=-1):
561 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000562
563 Returns an empty bytes object on EOF, or None if the object is
564 set not to block and has no data to read.
565 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300566 if size is None:
567 size = -1
568 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000569 return self.readall()
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300570 b = bytearray(size.__index__())
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000571 n = self.readinto(b)
Antoine Pitrou328ec742010-09-14 18:37:24 +0000572 if n is None:
573 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000574 del b[n:]
575 return bytes(b)
576
577 def readall(self):
578 """Read until EOF, using multiple read() call."""
579 res = bytearray()
580 while True:
581 data = self.read(DEFAULT_BUFFER_SIZE)
582 if not data:
583 break
584 res += data
Victor Stinnera80987f2011-05-25 22:47:16 +0200585 if res:
586 return bytes(res)
587 else:
588 # b'' or None
589 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000590
Raymond Hettinger3c940242011-01-12 23:39:31 +0000591 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000592 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000593
Raymond Hettingercbb80892011-01-13 18:15:51 +0000594 Returns an int representing the number of bytes read (0 for EOF), or
595 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000596 """
597 self._unsupported("readinto")
598
Raymond Hettinger3c940242011-01-12 23:39:31 +0000599 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000600 """Write the given buffer to the IO stream.
601
602 Returns the number of bytes written, which may be less than len(b).
603 """
604 self._unsupported("write")
605
606io.RawIOBase.register(RawIOBase)
607from _io import FileIO
608RawIOBase.register(FileIO)
609
610
611class BufferedIOBase(IOBase):
612
613 """Base class for buffered IO objects.
614
615 The main difference with RawIOBase is that the read() method
616 supports omitting the size argument, and does not have a default
617 implementation that defers to readinto().
618
619 In addition, read(), readinto() and write() may raise
620 BlockingIOError if the underlying raw stream is in non-blocking
621 mode and not ready; unlike their raw counterparts, they will never
622 return None.
623
624 A typical implementation should not inherit from a RawIOBase
625 implementation, but wrap one.
626 """
627
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300628 def read(self, size=None):
629 """Read and return up to size bytes, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000630
631 If the argument is omitted, None, or negative, reads and
632 returns all data until EOF.
633
634 If the argument is positive, and the underlying raw stream is
635 not 'interactive', multiple raw reads may be issued to satisfy
636 the byte count (unless EOF is reached first). But for
637 interactive raw streams (XXX and for pipes?), at most one raw
638 read will be issued, and a short result does not imply that
639 EOF is imminent.
640
641 Returns an empty bytes array on EOF.
642
643 Raises BlockingIOError if the underlying raw stream has no
644 data at the moment.
645 """
646 self._unsupported("read")
647
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300648 def read1(self, size=None):
649 """Read up to size bytes with at most one read() system call,
650 where size is an int.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000651 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000652 self._unsupported("read1")
653
Raymond Hettinger3c940242011-01-12 23:39:31 +0000654 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000655 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000656
657 Like read(), this may issue multiple reads to the underlying raw
658 stream, unless the latter is 'interactive'.
659
Raymond Hettingercbb80892011-01-13 18:15:51 +0000660 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000661
662 Raises BlockingIOError if the underlying raw stream has no
663 data at the moment.
664 """
665 # XXX This ought to work with anything that supports the buffer API
666 data = self.read(len(b))
667 n = len(data)
668 try:
669 b[:n] = data
670 except TypeError as err:
671 import array
672 if not isinstance(b, array.array):
673 raise err
674 b[:n] = array.array('b', data)
675 return n
676
Raymond Hettinger3c940242011-01-12 23:39:31 +0000677 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000678 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000679
680 Return the number of bytes written, which is never less than
681 len(b).
682
683 Raises BlockingIOError if the buffer is full and the
684 underlying raw stream cannot accept more data at the moment.
685 """
686 self._unsupported("write")
687
Raymond Hettinger3c940242011-01-12 23:39:31 +0000688 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000689 """
690 Separate the underlying raw stream from the buffer and return it.
691
692 After the raw stream has been detached, the buffer is in an unusable
693 state.
694 """
695 self._unsupported("detach")
696
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000697io.BufferedIOBase.register(BufferedIOBase)
698
699
700class _BufferedIOMixin(BufferedIOBase):
701
702 """A mixin implementation of BufferedIOBase with an underlying raw stream.
703
704 This passes most requests on to the underlying raw stream. It
705 does *not* provide implementations of read(), readinto() or
706 write().
707 """
708
709 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000710 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000711
712 ### Positioning ###
713
714 def seek(self, pos, whence=0):
715 new_position = self.raw.seek(pos, whence)
716 if new_position < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200717 raise OSError("seek() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000718 return new_position
719
720 def tell(self):
721 pos = self.raw.tell()
722 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200723 raise OSError("tell() returned an invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000724 return pos
725
726 def truncate(self, pos=None):
727 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
728 # and a flush may be necessary to synch both views of the current
729 # file state.
730 self.flush()
731
732 if pos is None:
733 pos = self.tell()
734 # XXX: Should seek() be used, instead of passing the position
735 # XXX directly to truncate?
736 return self.raw.truncate(pos)
737
738 ### Flush and close ###
739
740 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000741 if self.closed:
742 raise ValueError("flush of closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000743 self.raw.flush()
744
745 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000746 if self.raw is not None and not self.closed:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +0100747 try:
748 # may raise BlockingIOError or BrokenPipeError etc
749 self.flush()
750 finally:
751 self.raw.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000752
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000753 def detach(self):
754 if self.raw is None:
755 raise ValueError("raw stream already detached")
756 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000757 raw = self._raw
758 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000759 return raw
760
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000761 ### Inquiries ###
762
763 def seekable(self):
764 return self.raw.seekable()
765
766 def readable(self):
767 return self.raw.readable()
768
769 def writable(self):
770 return self.raw.writable()
771
772 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000773 def raw(self):
774 return self._raw
775
776 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000777 def closed(self):
778 return self.raw.closed
779
780 @property
781 def name(self):
782 return self.raw.name
783
784 @property
785 def mode(self):
786 return self.raw.mode
787
Antoine Pitrou243757e2010-11-05 21:15:39 +0000788 def __getstate__(self):
789 raise TypeError("can not serialize a '{0}' object"
790 .format(self.__class__.__name__))
791
Antoine Pitrou716c4442009-05-23 19:04:03 +0000792 def __repr__(self):
793 clsname = self.__class__.__name__
794 try:
795 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -0600796 except Exception:
Antoine Pitrou716c4442009-05-23 19:04:03 +0000797 return "<_pyio.{0}>".format(clsname)
798 else:
799 return "<_pyio.{0} name={1!r}>".format(clsname, name)
800
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000801 ### Lower-level APIs ###
802
803 def fileno(self):
804 return self.raw.fileno()
805
806 def isatty(self):
807 return self.raw.isatty()
808
809
810class BytesIO(BufferedIOBase):
811
812 """Buffered I/O implementation using an in-memory bytes buffer."""
813
814 def __init__(self, initial_bytes=None):
815 buf = bytearray()
816 if initial_bytes is not None:
817 buf += initial_bytes
818 self._buffer = buf
819 self._pos = 0
820
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000821 def __getstate__(self):
822 if self.closed:
823 raise ValueError("__getstate__ on closed file")
824 return self.__dict__.copy()
825
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000826 def getvalue(self):
827 """Return the bytes value (contents) of the buffer
828 """
829 if self.closed:
830 raise ValueError("getvalue on closed file")
831 return bytes(self._buffer)
832
Antoine Pitrou972ee132010-09-06 18:48:21 +0000833 def getbuffer(self):
834 """Return a readable and writable view of the buffer.
835 """
Serhiy Storchakac057c382015-02-03 02:00:18 +0200836 if self.closed:
837 raise ValueError("getbuffer on closed file")
Antoine Pitrou972ee132010-09-06 18:48:21 +0000838 return memoryview(self._buffer)
839
Serhiy Storchakac057c382015-02-03 02:00:18 +0200840 def close(self):
841 self._buffer.clear()
842 super().close()
843
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300844 def read(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000845 if self.closed:
846 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300847 if size is None:
848 size = -1
849 if size < 0:
850 size = len(self._buffer)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000851 if len(self._buffer) <= self._pos:
852 return b""
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300853 newpos = min(len(self._buffer), self._pos + size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000854 b = self._buffer[self._pos : newpos]
855 self._pos = newpos
856 return bytes(b)
857
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300858 def read1(self, size):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000859 """This is the same as read.
860 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300861 return self.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000862
863 def write(self, b):
864 if self.closed:
865 raise ValueError("write to closed file")
866 if isinstance(b, str):
867 raise TypeError("can't write str to binary stream")
868 n = len(b)
869 if n == 0:
870 return 0
871 pos = self._pos
872 if pos > len(self._buffer):
873 # Inserts null bytes between the current end of the file
874 # and the new write position.
875 padding = b'\x00' * (pos - len(self._buffer))
876 self._buffer += padding
877 self._buffer[pos:pos + n] = b
878 self._pos += n
879 return n
880
881 def seek(self, pos, whence=0):
882 if self.closed:
883 raise ValueError("seek on closed file")
884 try:
Florent Xiclunab14930c2010-03-13 15:26:44 +0000885 pos.__index__
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000886 except AttributeError as err:
887 raise TypeError("an integer is required") from err
888 if whence == 0:
889 if pos < 0:
890 raise ValueError("negative seek position %r" % (pos,))
891 self._pos = pos
892 elif whence == 1:
893 self._pos = max(0, self._pos + pos)
894 elif whence == 2:
895 self._pos = max(0, len(self._buffer) + pos)
896 else:
Jesus Cea94363612012-06-22 18:32:07 +0200897 raise ValueError("unsupported whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000898 return self._pos
899
900 def tell(self):
901 if self.closed:
902 raise ValueError("tell on closed file")
903 return self._pos
904
905 def truncate(self, pos=None):
906 if self.closed:
907 raise ValueError("truncate on closed file")
908 if pos is None:
909 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000910 else:
911 try:
912 pos.__index__
913 except AttributeError as err:
914 raise TypeError("an integer is required") from err
915 if pos < 0:
916 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000917 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000918 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000919
920 def readable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200921 if self.closed:
922 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000923 return True
924
925 def writable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200926 if self.closed:
927 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000928 return True
929
930 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200931 if self.closed:
932 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000933 return True
934
935
936class BufferedReader(_BufferedIOMixin):
937
938 """BufferedReader(raw[, buffer_size])
939
940 A buffer for a readable, sequential BaseRawIO object.
941
942 The constructor creates a BufferedReader for the given readable raw
943 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
944 is used.
945 """
946
947 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
948 """Create a new buffered reader using the given readable raw IO object.
949 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000950 if not raw.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200951 raise OSError('"raw" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000952
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000953 _BufferedIOMixin.__init__(self, raw)
954 if buffer_size <= 0:
955 raise ValueError("invalid buffer size")
956 self.buffer_size = buffer_size
957 self._reset_read_buf()
958 self._read_lock = Lock()
959
960 def _reset_read_buf(self):
961 self._read_buf = b""
962 self._read_pos = 0
963
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300964 def read(self, size=None):
965 """Read size bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000966
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300967 Returns exactly size bytes of data unless the underlying raw IO
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000968 stream reaches EOF or if the call would block in non-blocking
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300969 mode. If size is negative, read until EOF or until read() would
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000970 block.
971 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300972 if size is not None and size < -1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000973 raise ValueError("invalid number of bytes to read")
974 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300975 return self._read_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000976
977 def _read_unlocked(self, n=None):
978 nodata_val = b""
979 empty_values = (b"", None)
980 buf = self._read_buf
981 pos = self._read_pos
982
983 # Special case for when the number of bytes to read is unspecified.
984 if n is None or n == -1:
985 self._reset_read_buf()
Victor Stinnerb57f1082011-05-26 00:19:38 +0200986 if hasattr(self.raw, 'readall'):
987 chunk = self.raw.readall()
988 if chunk is None:
989 return buf[pos:] or None
990 else:
991 return buf[pos:] + chunk
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000992 chunks = [buf[pos:]] # Strip the consumed bytes.
993 current_size = 0
994 while True:
995 # Read until EOF or until read() would block.
Antoine Pitrou707ce822011-02-25 21:24:11 +0000996 try:
997 chunk = self.raw.read()
Antoine Pitrou24d659d2011-10-23 23:49:42 +0200998 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +0000999 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001000 if chunk in empty_values:
1001 nodata_val = chunk
1002 break
1003 current_size += len(chunk)
1004 chunks.append(chunk)
1005 return b"".join(chunks) or nodata_val
1006
1007 # The number of bytes to read is specified, return at most n bytes.
1008 avail = len(buf) - pos # Length of the available buffered data.
1009 if n <= avail:
1010 # Fast path: the data to read is fully buffered.
1011 self._read_pos += n
1012 return buf[pos:pos+n]
1013 # Slow path: read from the stream until enough bytes are read,
1014 # or until an EOF occurs or until read() would block.
1015 chunks = [buf[pos:]]
1016 wanted = max(self.buffer_size, n)
1017 while avail < n:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001018 try:
1019 chunk = self.raw.read(wanted)
Antoine Pitrou24d659d2011-10-23 23:49:42 +02001020 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001021 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001022 if chunk in empty_values:
1023 nodata_val = chunk
1024 break
1025 avail += len(chunk)
1026 chunks.append(chunk)
1027 # n is more then avail only when an EOF occurred or when
1028 # read() would have blocked.
1029 n = min(n, avail)
1030 out = b"".join(chunks)
1031 self._read_buf = out[n:] # Save the extra data in the buffer.
1032 self._read_pos = 0
1033 return out[:n] if out else nodata_val
1034
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001035 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001036 """Returns buffered bytes without advancing the position.
1037
1038 The argument indicates a desired minimal number of bytes; we
1039 do at most one raw read to satisfy it. We never return more
1040 than self.buffer_size.
1041 """
1042 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001043 return self._peek_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001044
1045 def _peek_unlocked(self, n=0):
1046 want = min(n, self.buffer_size)
1047 have = len(self._read_buf) - self._read_pos
1048 if have < want or have <= 0:
1049 to_read = self.buffer_size - have
Antoine Pitrou707ce822011-02-25 21:24:11 +00001050 while True:
1051 try:
1052 current = self.raw.read(to_read)
Antoine Pitrou24d659d2011-10-23 23:49:42 +02001053 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001054 continue
1055 break
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001056 if current:
1057 self._read_buf = self._read_buf[self._read_pos:] + current
1058 self._read_pos = 0
1059 return self._read_buf[self._read_pos:]
1060
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001061 def read1(self, size):
1062 """Reads up to size bytes, with at most one read() system call."""
1063 # Returns up to size bytes. If at least one byte is buffered, we
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001064 # only return buffered bytes. Otherwise, we do one raw read.
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001065 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001066 raise ValueError("number of bytes to read must be positive")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001067 if size == 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001068 return b""
1069 with self._read_lock:
1070 self._peek_unlocked(1)
1071 return self._read_unlocked(
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001072 min(size, len(self._read_buf) - self._read_pos))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001073
1074 def tell(self):
1075 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1076
1077 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001078 if whence not in valid_seek_flags:
Jesus Cea990eff02012-04-26 17:05:31 +02001079 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001080 with self._read_lock:
1081 if whence == 1:
1082 pos -= len(self._read_buf) - self._read_pos
1083 pos = _BufferedIOMixin.seek(self, pos, whence)
1084 self._reset_read_buf()
1085 return pos
1086
1087class BufferedWriter(_BufferedIOMixin):
1088
1089 """A buffer for a writeable sequential RawIO object.
1090
1091 The constructor creates a BufferedWriter for the given writeable raw
1092 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001093 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001094 """
1095
Florent Xicluna109d5732012-07-07 17:03:22 +02001096 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001097 if not raw.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001098 raise OSError('"raw" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001099
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001100 _BufferedIOMixin.__init__(self, raw)
1101 if buffer_size <= 0:
1102 raise ValueError("invalid buffer size")
1103 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001104 self._write_buf = bytearray()
1105 self._write_lock = Lock()
1106
1107 def write(self, b):
1108 if self.closed:
1109 raise ValueError("write to closed file")
1110 if isinstance(b, str):
1111 raise TypeError("can't write str to binary stream")
1112 with self._write_lock:
1113 # XXX we can implement some more tricks to try and avoid
1114 # partial writes
1115 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001116 # We're full, so let's pre-flush the buffer. (This may
1117 # raise BlockingIOError with characters_written == 0.)
1118 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001119 before = len(self._write_buf)
1120 self._write_buf.extend(b)
1121 written = len(self._write_buf) - before
1122 if len(self._write_buf) > self.buffer_size:
1123 try:
1124 self._flush_unlocked()
1125 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001126 if len(self._write_buf) > self.buffer_size:
1127 # We've hit the buffer_size. We have to accept a partial
1128 # write and cut back our buffer.
1129 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001130 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001131 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001132 raise BlockingIOError(e.errno, e.strerror, written)
1133 return written
1134
1135 def truncate(self, pos=None):
1136 with self._write_lock:
1137 self._flush_unlocked()
1138 if pos is None:
1139 pos = self.raw.tell()
1140 return self.raw.truncate(pos)
1141
1142 def flush(self):
1143 with self._write_lock:
1144 self._flush_unlocked()
1145
1146 def _flush_unlocked(self):
1147 if self.closed:
1148 raise ValueError("flush of closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001149 while self._write_buf:
1150 try:
1151 n = self.raw.write(self._write_buf)
Antoine Pitrou7fe601c2011-11-21 20:22:01 +01001152 except InterruptedError:
1153 continue
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001154 except BlockingIOError:
1155 raise RuntimeError("self.raw should implement RawIOBase: it "
1156 "should not raise BlockingIOError")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001157 if n is None:
1158 raise BlockingIOError(
1159 errno.EAGAIN,
1160 "write could not complete without blocking", 0)
1161 if n > len(self._write_buf) or n < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001162 raise OSError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001163 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001164
1165 def tell(self):
1166 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1167
1168 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001169 if whence not in valid_seek_flags:
1170 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001171 with self._write_lock:
1172 self._flush_unlocked()
1173 return _BufferedIOMixin.seek(self, pos, whence)
1174
1175
1176class BufferedRWPair(BufferedIOBase):
1177
1178 """A buffered reader and writer object together.
1179
1180 A buffered reader object and buffered writer object put together to
1181 form a sequential IO object that can read and write. This is typically
1182 used with a socket or two-way pipe.
1183
1184 reader and writer are RawIOBase objects that are readable and
1185 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001186 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001187 """
1188
1189 # XXX The usefulness of this (compared to having two separate IO
1190 # objects) is questionable.
1191
Florent Xicluna109d5732012-07-07 17:03:22 +02001192 def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001193 """Constructor.
1194
1195 The arguments are two RawIO instances.
1196 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001197 if not reader.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001198 raise OSError('"reader" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001199
1200 if not writer.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001201 raise OSError('"writer" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001202
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001203 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001204 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001205
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001206 def read(self, size=None):
1207 if size is None:
1208 size = -1
1209 return self.reader.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001210
1211 def readinto(self, b):
1212 return self.reader.readinto(b)
1213
1214 def write(self, b):
1215 return self.writer.write(b)
1216
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001217 def peek(self, size=0):
1218 return self.reader.peek(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001219
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001220 def read1(self, size):
1221 return self.reader.read1(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001222
1223 def readable(self):
1224 return self.reader.readable()
1225
1226 def writable(self):
1227 return self.writer.writable()
1228
1229 def flush(self):
1230 return self.writer.flush()
1231
1232 def close(self):
1233 self.writer.close()
1234 self.reader.close()
1235
1236 def isatty(self):
1237 return self.reader.isatty() or self.writer.isatty()
1238
1239 @property
1240 def closed(self):
1241 return self.writer.closed
1242
1243
1244class BufferedRandom(BufferedWriter, BufferedReader):
1245
1246 """A buffered interface to random access streams.
1247
1248 The constructor creates a reader and writer for a seekable stream,
1249 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001250 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001251 """
1252
Florent Xicluna109d5732012-07-07 17:03:22 +02001253 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001254 raw._checkSeekable()
1255 BufferedReader.__init__(self, raw, buffer_size)
Florent Xicluna109d5732012-07-07 17:03:22 +02001256 BufferedWriter.__init__(self, raw, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001257
1258 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001259 if whence not in valid_seek_flags:
1260 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001261 self.flush()
1262 if self._read_buf:
1263 # Undo read ahead.
1264 with self._read_lock:
1265 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1266 # First do the raw seek, then empty the read buffer, so that
1267 # if the raw seek fails, we don't lose buffered data forever.
1268 pos = self.raw.seek(pos, whence)
1269 with self._read_lock:
1270 self._reset_read_buf()
1271 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001272 raise OSError("seek() returned invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001273 return pos
1274
1275 def tell(self):
1276 if self._write_buf:
1277 return BufferedWriter.tell(self)
1278 else:
1279 return BufferedReader.tell(self)
1280
1281 def truncate(self, pos=None):
1282 if pos is None:
1283 pos = self.tell()
1284 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001285 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001286
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001287 def read(self, size=None):
1288 if size is None:
1289 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001290 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001291 return BufferedReader.read(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001292
1293 def readinto(self, b):
1294 self.flush()
1295 return BufferedReader.readinto(self, b)
1296
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001297 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001298 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001299 return BufferedReader.peek(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001300
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001301 def read1(self, size):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001302 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001303 return BufferedReader.read1(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001304
1305 def write(self, b):
1306 if self._read_buf:
1307 # Undo readahead
1308 with self._read_lock:
1309 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1310 self._reset_read_buf()
1311 return BufferedWriter.write(self, b)
1312
1313
1314class TextIOBase(IOBase):
1315
1316 """Base class for text I/O.
1317
1318 This class provides a character and line based interface to stream
1319 I/O. There is no readinto method because Python's character strings
1320 are immutable. There is no public constructor.
1321 """
1322
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001323 def read(self, size=-1):
1324 """Read at most size characters from stream, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001325
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001326 Read from underlying buffer until we have size characters or we hit EOF.
1327 If size is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001328
1329 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001330 """
1331 self._unsupported("read")
1332
Raymond Hettinger3c940242011-01-12 23:39:31 +00001333 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001334 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001335 self._unsupported("write")
1336
Georg Brandl4d73b572011-01-13 07:13:06 +00001337 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001338 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001339 self._unsupported("truncate")
1340
Raymond Hettinger3c940242011-01-12 23:39:31 +00001341 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001342 """Read until newline or EOF.
1343
1344 Returns an empty string if EOF is hit immediately.
1345 """
1346 self._unsupported("readline")
1347
Raymond Hettinger3c940242011-01-12 23:39:31 +00001348 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001349 """
1350 Separate the underlying buffer from the TextIOBase and return it.
1351
1352 After the underlying buffer has been detached, the TextIO is in an
1353 unusable state.
1354 """
1355 self._unsupported("detach")
1356
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001357 @property
1358 def encoding(self):
1359 """Subclasses should override."""
1360 return None
1361
1362 @property
1363 def newlines(self):
1364 """Line endings translated so far.
1365
1366 Only line endings translated during reading are considered.
1367
1368 Subclasses should override.
1369 """
1370 return None
1371
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001372 @property
1373 def errors(self):
1374 """Error setting of the decoder or encoder.
1375
1376 Subclasses should override."""
1377 return None
1378
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001379io.TextIOBase.register(TextIOBase)
1380
1381
1382class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1383 r"""Codec used when reading a file in universal newlines mode. It wraps
1384 another incremental decoder, translating \r\n and \r into \n. It also
1385 records the types of newlines encountered. When used with
1386 translate=False, it ensures that the newline sequence is returned in
1387 one piece.
1388 """
1389 def __init__(self, decoder, translate, errors='strict'):
1390 codecs.IncrementalDecoder.__init__(self, errors=errors)
1391 self.translate = translate
1392 self.decoder = decoder
1393 self.seennl = 0
1394 self.pendingcr = False
1395
1396 def decode(self, input, final=False):
1397 # decode input (with the eventual \r from a previous pass)
1398 if self.decoder is None:
1399 output = input
1400 else:
1401 output = self.decoder.decode(input, final=final)
1402 if self.pendingcr and (output or final):
1403 output = "\r" + output
1404 self.pendingcr = False
1405
1406 # retain last \r even when not translating data:
1407 # then readline() is sure to get \r\n in one pass
1408 if output.endswith("\r") and not final:
1409 output = output[:-1]
1410 self.pendingcr = True
1411
1412 # Record which newlines are read
1413 crlf = output.count('\r\n')
1414 cr = output.count('\r') - crlf
1415 lf = output.count('\n') - crlf
1416 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1417 | (crlf and self._CRLF)
1418
1419 if self.translate:
1420 if crlf:
1421 output = output.replace("\r\n", "\n")
1422 if cr:
1423 output = output.replace("\r", "\n")
1424
1425 return output
1426
1427 def getstate(self):
1428 if self.decoder is None:
1429 buf = b""
1430 flag = 0
1431 else:
1432 buf, flag = self.decoder.getstate()
1433 flag <<= 1
1434 if self.pendingcr:
1435 flag |= 1
1436 return buf, flag
1437
1438 def setstate(self, state):
1439 buf, flag = state
1440 self.pendingcr = bool(flag & 1)
1441 if self.decoder is not None:
1442 self.decoder.setstate((buf, flag >> 1))
1443
1444 def reset(self):
1445 self.seennl = 0
1446 self.pendingcr = False
1447 if self.decoder is not None:
1448 self.decoder.reset()
1449
1450 _LF = 1
1451 _CR = 2
1452 _CRLF = 4
1453
1454 @property
1455 def newlines(self):
1456 return (None,
1457 "\n",
1458 "\r",
1459 ("\r", "\n"),
1460 "\r\n",
1461 ("\n", "\r\n"),
1462 ("\r", "\r\n"),
1463 ("\r", "\n", "\r\n")
1464 )[self.seennl]
1465
1466
1467class TextIOWrapper(TextIOBase):
1468
1469 r"""Character and line based layer over a BufferedIOBase object, buffer.
1470
1471 encoding gives the name of the encoding that the stream will be
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001472 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001473
1474 errors determines the strictness of encoding and decoding (see the
1475 codecs.register) and defaults to "strict".
1476
1477 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1478 handling of line endings. If it is None, universal newlines is
1479 enabled. With this enabled, on input, the lines endings '\n', '\r',
1480 or '\r\n' are translated to '\n' before being returned to the
1481 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001482 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001483 legal values, that newline becomes the newline when the file is read
1484 and it is returned untranslated. On output, '\n' is converted to the
1485 newline.
1486
1487 If line_buffering is True, a call to flush is implied when a call to
1488 write contains a newline character.
1489 """
1490
1491 _CHUNK_SIZE = 2048
1492
Andrew Svetlov4e9e9c12012-08-13 16:09:54 +03001493 # The write_through argument has no effect here since this
1494 # implementation always writes through. The argument is present only
1495 # so that the signature can match the signature of the C version.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001496 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001497 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001498 if newline is not None and not isinstance(newline, str):
1499 raise TypeError("illegal newline type: %r" % (type(newline),))
1500 if newline not in (None, "", "\n", "\r", "\r\n"):
1501 raise ValueError("illegal newline value: %r" % (newline,))
1502 if encoding is None:
1503 try:
1504 encoding = os.device_encoding(buffer.fileno())
1505 except (AttributeError, UnsupportedOperation):
1506 pass
1507 if encoding is None:
1508 try:
1509 import locale
Brett Cannoncd171c82013-07-04 17:43:24 -04001510 except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001511 # Importing locale may fail if Python is being built
1512 encoding = "ascii"
1513 else:
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001514 encoding = locale.getpreferredencoding(False)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001515
1516 if not isinstance(encoding, str):
1517 raise ValueError("invalid encoding: %r" % encoding)
1518
Nick Coghlana9b15242014-02-04 22:11:18 +10001519 if not codecs.lookup(encoding)._is_text_encoding:
1520 msg = ("%r is not a text encoding; "
1521 "use codecs.open() to handle arbitrary codecs")
1522 raise LookupError(msg % encoding)
1523
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001524 if errors is None:
1525 errors = "strict"
1526 else:
1527 if not isinstance(errors, str):
1528 raise ValueError("invalid errors: %r" % errors)
1529
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001530 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001531 self._line_buffering = line_buffering
1532 self._encoding = encoding
1533 self._errors = errors
1534 self._readuniversal = not newline
1535 self._readtranslate = newline is None
1536 self._readnl = newline
1537 self._writetranslate = newline != ''
1538 self._writenl = newline or os.linesep
1539 self._encoder = None
1540 self._decoder = None
1541 self._decoded_chars = '' # buffer for text returned from decoder
1542 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1543 self._snapshot = None # info for reconstructing decoder state
1544 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001545 self._has_read1 = hasattr(self.buffer, 'read1')
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001546 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001547
Antoine Pitroue4501852009-05-14 18:55:55 +00001548 if self._seekable and self.writable():
1549 position = self.buffer.tell()
1550 if position != 0:
1551 try:
1552 self._get_encoder().setstate(0)
1553 except LookupError:
1554 # Sometimes the encoder doesn't exist
1555 pass
1556
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001557 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1558 # where dec_flags is the second (integer) item of the decoder state
1559 # and next_input is the chunk of input bytes that comes next after the
1560 # snapshot point. We use this to reconstruct decoder states in tell().
1561
1562 # Naming convention:
1563 # - "bytes_..." for integer variables that count input bytes
1564 # - "chars_..." for integer variables that count decoded characters
1565
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001566 def __repr__(self):
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001567 result = "<_pyio.TextIOWrapper"
Antoine Pitrou716c4442009-05-23 19:04:03 +00001568 try:
1569 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -06001570 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001571 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00001572 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001573 result += " name={0!r}".format(name)
1574 try:
1575 mode = self.mode
Benjamin Peterson10e76b62014-12-21 20:51:50 -06001576 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001577 pass
1578 else:
1579 result += " mode={0!r}".format(mode)
1580 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001581
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001582 @property
1583 def encoding(self):
1584 return self._encoding
1585
1586 @property
1587 def errors(self):
1588 return self._errors
1589
1590 @property
1591 def line_buffering(self):
1592 return self._line_buffering
1593
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001594 @property
1595 def buffer(self):
1596 return self._buffer
1597
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001598 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02001599 if self.closed:
1600 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001601 return self._seekable
1602
1603 def readable(self):
1604 return self.buffer.readable()
1605
1606 def writable(self):
1607 return self.buffer.writable()
1608
1609 def flush(self):
1610 self.buffer.flush()
1611 self._telling = self._seekable
1612
1613 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00001614 if self.buffer is not None and not self.closed:
Benjamin Peterson68623612012-12-20 11:53:11 -06001615 try:
1616 self.flush()
1617 finally:
1618 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001619
1620 @property
1621 def closed(self):
1622 return self.buffer.closed
1623
1624 @property
1625 def name(self):
1626 return self.buffer.name
1627
1628 def fileno(self):
1629 return self.buffer.fileno()
1630
1631 def isatty(self):
1632 return self.buffer.isatty()
1633
Raymond Hettinger00fa0392011-01-13 02:52:26 +00001634 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001635 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001636 if self.closed:
1637 raise ValueError("write to closed file")
1638 if not isinstance(s, str):
1639 raise TypeError("can't write %s to text stream" %
1640 s.__class__.__name__)
1641 length = len(s)
1642 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1643 if haslf and self._writetranslate and self._writenl != "\n":
1644 s = s.replace("\n", self._writenl)
1645 encoder = self._encoder or self._get_encoder()
1646 # XXX What if we were just reading?
1647 b = encoder.encode(s)
1648 self.buffer.write(b)
1649 if self._line_buffering and (haslf or "\r" in s):
1650 self.flush()
1651 self._snapshot = None
1652 if self._decoder:
1653 self._decoder.reset()
1654 return length
1655
1656 def _get_encoder(self):
1657 make_encoder = codecs.getincrementalencoder(self._encoding)
1658 self._encoder = make_encoder(self._errors)
1659 return self._encoder
1660
1661 def _get_decoder(self):
1662 make_decoder = codecs.getincrementaldecoder(self._encoding)
1663 decoder = make_decoder(self._errors)
1664 if self._readuniversal:
1665 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1666 self._decoder = decoder
1667 return decoder
1668
1669 # The following three methods implement an ADT for _decoded_chars.
1670 # Text returned from the decoder is buffered here until the client
1671 # requests it by calling our read() or readline() method.
1672 def _set_decoded_chars(self, chars):
1673 """Set the _decoded_chars buffer."""
1674 self._decoded_chars = chars
1675 self._decoded_chars_used = 0
1676
1677 def _get_decoded_chars(self, n=None):
1678 """Advance into the _decoded_chars buffer."""
1679 offset = self._decoded_chars_used
1680 if n is None:
1681 chars = self._decoded_chars[offset:]
1682 else:
1683 chars = self._decoded_chars[offset:offset + n]
1684 self._decoded_chars_used += len(chars)
1685 return chars
1686
1687 def _rewind_decoded_chars(self, n):
1688 """Rewind the _decoded_chars buffer."""
1689 if self._decoded_chars_used < n:
1690 raise AssertionError("rewind decoded_chars out of bounds")
1691 self._decoded_chars_used -= n
1692
1693 def _read_chunk(self):
1694 """
1695 Read and decode the next chunk of data from the BufferedReader.
1696 """
1697
1698 # The return value is True unless EOF was reached. The decoded
1699 # string is placed in self._decoded_chars (replacing its previous
1700 # value). The entire input chunk is sent to the decoder, though
1701 # some of it may remain buffered in the decoder, yet to be
1702 # converted.
1703
1704 if self._decoder is None:
1705 raise ValueError("no decoder")
1706
1707 if self._telling:
1708 # To prepare for tell(), we need to snapshot a point in the
1709 # file where the decoder's input buffer is empty.
1710
1711 dec_buffer, dec_flags = self._decoder.getstate()
1712 # Given this, we know there was a valid snapshot point
1713 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1714
1715 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02001716 if self._has_read1:
1717 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1718 else:
1719 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001720 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001721 decoded_chars = self._decoder.decode(input_chunk, eof)
1722 self._set_decoded_chars(decoded_chars)
1723 if decoded_chars:
1724 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
1725 else:
1726 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001727
1728 if self._telling:
1729 # At the snapshot point, len(dec_buffer) bytes before the read,
1730 # the next input to be decoded is dec_buffer + input_chunk.
1731 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1732
1733 return not eof
1734
1735 def _pack_cookie(self, position, dec_flags=0,
1736 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1737 # The meaning of a tell() cookie is: seek to position, set the
1738 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1739 # into the decoder with need_eof as the EOF flag, then skip
1740 # chars_to_skip characters of the decoded result. For most simple
1741 # decoders, tell() will often just give a byte offset in the file.
1742 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1743 (chars_to_skip<<192) | bool(need_eof)<<256)
1744
1745 def _unpack_cookie(self, bigint):
1746 rest, position = divmod(bigint, 1<<64)
1747 rest, dec_flags = divmod(rest, 1<<64)
1748 rest, bytes_to_feed = divmod(rest, 1<<64)
1749 need_eof, chars_to_skip = divmod(rest, 1<<64)
1750 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1751
1752 def tell(self):
1753 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001754 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001755 if not self._telling:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001756 raise OSError("telling position disabled by next() call")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001757 self.flush()
1758 position = self.buffer.tell()
1759 decoder = self._decoder
1760 if decoder is None or self._snapshot is None:
1761 if self._decoded_chars:
1762 # This should never happen.
1763 raise AssertionError("pending decoded text")
1764 return position
1765
1766 # Skip backward to the snapshot point (see _read_chunk).
1767 dec_flags, next_input = self._snapshot
1768 position -= len(next_input)
1769
1770 # How many decoded characters have been used up since the snapshot?
1771 chars_to_skip = self._decoded_chars_used
1772 if chars_to_skip == 0:
1773 # We haven't moved from the snapshot point.
1774 return self._pack_cookie(position, dec_flags)
1775
1776 # Starting from the snapshot position, we will walk the decoder
1777 # forward until it gives us enough decoded characters.
1778 saved_state = decoder.getstate()
1779 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001780 # Fast search for an acceptable start point, close to our
1781 # current pos.
1782 # Rationale: calling decoder.decode() has a large overhead
1783 # regardless of chunk size; we want the number of such calls to
1784 # be O(1) in most situations (common decoders, non-crazy input).
1785 # Actually, it will be exactly 1 for fixed-size codecs (all
1786 # 8-bit codecs, also UTF-16 and UTF-32).
1787 skip_bytes = int(self._b2cratio * chars_to_skip)
1788 skip_back = 1
1789 assert skip_bytes <= len(next_input)
1790 while skip_bytes > 0:
1791 decoder.setstate((b'', dec_flags))
1792 # Decode up to temptative start point
1793 n = len(decoder.decode(next_input[:skip_bytes]))
1794 if n <= chars_to_skip:
1795 b, d = decoder.getstate()
1796 if not b:
1797 # Before pos and no bytes buffered in decoder => OK
1798 dec_flags = d
1799 chars_to_skip -= n
1800 break
1801 # Skip back by buffered amount and reset heuristic
1802 skip_bytes -= len(b)
1803 skip_back = 1
1804 else:
1805 # We're too far ahead, skip back a bit
1806 skip_bytes -= skip_back
1807 skip_back = skip_back * 2
1808 else:
1809 skip_bytes = 0
1810 decoder.setstate((b'', dec_flags))
1811
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001812 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001813 start_pos = position + skip_bytes
1814 start_flags = dec_flags
1815 if chars_to_skip == 0:
1816 # We haven't moved from the start point.
1817 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001818
1819 # Feed the decoder one byte at a time. As we go, note the
1820 # nearest "safe start point" before the current location
1821 # (a point where the decoder has nothing buffered, so seek()
1822 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001823 bytes_fed = 0
1824 need_eof = 0
1825 # Chars decoded since `start_pos`
1826 chars_decoded = 0
1827 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001828 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001829 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001830 dec_buffer, dec_flags = decoder.getstate()
1831 if not dec_buffer and chars_decoded <= chars_to_skip:
1832 # Decoder buffer is empty, so this is a safe start point.
1833 start_pos += bytes_fed
1834 chars_to_skip -= chars_decoded
1835 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1836 if chars_decoded >= chars_to_skip:
1837 break
1838 else:
1839 # We didn't get enough decoded data; signal EOF to get more.
1840 chars_decoded += len(decoder.decode(b'', final=True))
1841 need_eof = 1
1842 if chars_decoded < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001843 raise OSError("can't reconstruct logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001844
1845 # The returned cookie corresponds to the last safe start point.
1846 return self._pack_cookie(
1847 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1848 finally:
1849 decoder.setstate(saved_state)
1850
1851 def truncate(self, pos=None):
1852 self.flush()
1853 if pos is None:
1854 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001855 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001856
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001857 def detach(self):
1858 if self.buffer is None:
1859 raise ValueError("buffer is already detached")
1860 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001861 buffer = self._buffer
1862 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001863 return buffer
1864
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001865 def seek(self, cookie, whence=0):
1866 if self.closed:
1867 raise ValueError("tell on closed file")
1868 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001869 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001870 if whence == 1: # seek relative to current position
1871 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001872 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001873 # Seeking to the current position should attempt to
1874 # sync the underlying buffer with the current position.
1875 whence = 0
1876 cookie = self.tell()
1877 if whence == 2: # seek relative to end of file
1878 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001879 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001880 self.flush()
1881 position = self.buffer.seek(0, 2)
1882 self._set_decoded_chars('')
1883 self._snapshot = None
1884 if self._decoder:
1885 self._decoder.reset()
1886 return position
1887 if whence != 0:
Jesus Cea94363612012-06-22 18:32:07 +02001888 raise ValueError("unsupported whence (%r)" % (whence,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001889 if cookie < 0:
1890 raise ValueError("negative seek position %r" % (cookie,))
1891 self.flush()
1892
1893 # The strategy of seek() is to go back to the safe start point
1894 # and replay the effect of read(chars_to_skip) from there.
1895 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1896 self._unpack_cookie(cookie)
1897
1898 # Seek back to the safe start point.
1899 self.buffer.seek(start_pos)
1900 self._set_decoded_chars('')
1901 self._snapshot = None
1902
1903 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001904 if cookie == 0 and self._decoder:
1905 self._decoder.reset()
1906 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001907 self._decoder = self._decoder or self._get_decoder()
1908 self._decoder.setstate((b'', dec_flags))
1909 self._snapshot = (dec_flags, b'')
1910
1911 if chars_to_skip:
1912 # Just like _read_chunk, feed the decoder and save a snapshot.
1913 input_chunk = self.buffer.read(bytes_to_feed)
1914 self._set_decoded_chars(
1915 self._decoder.decode(input_chunk, need_eof))
1916 self._snapshot = (dec_flags, input_chunk)
1917
1918 # Skip chars_to_skip of the decoded characters.
1919 if len(self._decoded_chars) < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001920 raise OSError("can't restore logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001921 self._decoded_chars_used = chars_to_skip
1922
Antoine Pitroue4501852009-05-14 18:55:55 +00001923 # Finally, reset the encoder (merely useful for proper BOM handling)
1924 try:
1925 encoder = self._encoder or self._get_encoder()
1926 except LookupError:
1927 # Sometimes the encoder doesn't exist
1928 pass
1929 else:
1930 if cookie != 0:
1931 encoder.setstate(0)
1932 else:
1933 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001934 return cookie
1935
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001936 def read(self, size=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00001937 self._checkReadable()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001938 if size is None:
1939 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001940 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00001941 try:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001942 size.__index__
Florent Xiclunab14930c2010-03-13 15:26:44 +00001943 except AttributeError as err:
1944 raise TypeError("an integer is required") from err
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001945 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001946 # Read everything.
1947 result = (self._get_decoded_chars() +
1948 decoder.decode(self.buffer.read(), final=True))
1949 self._set_decoded_chars('')
1950 self._snapshot = None
1951 return result
1952 else:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001953 # Keep reading chunks until we have size characters to return.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001954 eof = False
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001955 result = self._get_decoded_chars(size)
1956 while len(result) < size and not eof:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001957 eof = not self._read_chunk()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001958 result += self._get_decoded_chars(size - len(result))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001959 return result
1960
1961 def __next__(self):
1962 self._telling = False
1963 line = self.readline()
1964 if not line:
1965 self._snapshot = None
1966 self._telling = self._seekable
1967 raise StopIteration
1968 return line
1969
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001970 def readline(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001971 if self.closed:
1972 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001973 if size is None:
1974 size = -1
1975 elif not isinstance(size, int):
1976 raise TypeError("size must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001977
1978 # Grab all the decoded text (we will rewind any extra bits later).
1979 line = self._get_decoded_chars()
1980
1981 start = 0
1982 # Make the decoder if it doesn't already exist.
1983 if not self._decoder:
1984 self._get_decoder()
1985
1986 pos = endpos = None
1987 while True:
1988 if self._readtranslate:
1989 # Newlines are already translated, only search for \n
1990 pos = line.find('\n', start)
1991 if pos >= 0:
1992 endpos = pos + 1
1993 break
1994 else:
1995 start = len(line)
1996
1997 elif self._readuniversal:
1998 # Universal newline search. Find any of \r, \r\n, \n
1999 # The decoder ensures that \r\n are not split in two pieces
2000
2001 # In C we'd look for these in parallel of course.
2002 nlpos = line.find("\n", start)
2003 crpos = line.find("\r", start)
2004 if crpos == -1:
2005 if nlpos == -1:
2006 # Nothing found
2007 start = len(line)
2008 else:
2009 # Found \n
2010 endpos = nlpos + 1
2011 break
2012 elif nlpos == -1:
2013 # Found lone \r
2014 endpos = crpos + 1
2015 break
2016 elif nlpos < crpos:
2017 # Found \n
2018 endpos = nlpos + 1
2019 break
2020 elif nlpos == crpos + 1:
2021 # Found \r\n
2022 endpos = crpos + 2
2023 break
2024 else:
2025 # Found \r
2026 endpos = crpos + 1
2027 break
2028 else:
2029 # non-universal
2030 pos = line.find(self._readnl)
2031 if pos >= 0:
2032 endpos = pos + len(self._readnl)
2033 break
2034
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002035 if size >= 0 and len(line) >= size:
2036 endpos = size # reached length size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002037 break
2038
2039 # No line ending seen yet - get more data'
2040 while self._read_chunk():
2041 if self._decoded_chars:
2042 break
2043 if self._decoded_chars:
2044 line += self._get_decoded_chars()
2045 else:
2046 # end of file
2047 self._set_decoded_chars('')
2048 self._snapshot = None
2049 return line
2050
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002051 if size >= 0 and endpos > size:
2052 endpos = size # don't exceed size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002053
2054 # Rewind _decoded_chars to just after the line ending we found.
2055 self._rewind_decoded_chars(len(line) - endpos)
2056 return line[:endpos]
2057
2058 @property
2059 def newlines(self):
2060 return self._decoder.newlines if self._decoder else None
2061
2062
2063class StringIO(TextIOWrapper):
2064 """Text I/O implementation using an in-memory buffer.
2065
2066 The initial_value argument sets the value of object. The newline
2067 argument is like the one of TextIOWrapper's constructor.
2068 """
2069
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002070 def __init__(self, initial_value="", newline="\n"):
2071 super(StringIO, self).__init__(BytesIO(),
2072 encoding="utf-8",
Serhiy Storchakac92ea762014-01-29 11:33:26 +02002073 errors="surrogatepass",
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002074 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002075 # Issue #5645: make universal newlines semantics the same as in the
2076 # C version, even under Windows.
2077 if newline is None:
2078 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002079 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002080 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002081 raise TypeError("initial_value must be str or None, not {0}"
2082 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002083 self.write(initial_value)
2084 self.seek(0)
2085
2086 def getvalue(self):
2087 self.flush()
Antoine Pitrou57839a62014-02-02 23:37:29 +01002088 decoder = self._decoder or self._get_decoder()
2089 old_state = decoder.getstate()
2090 decoder.reset()
2091 try:
2092 return decoder.decode(self.buffer.getvalue(), final=True)
2093 finally:
2094 decoder.setstate(old_state)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002095
2096 def __repr__(self):
2097 # TextIOWrapper tells the encoding in its repr. In StringIO,
2098 # that's a implementation detail.
2099 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002100
2101 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002102 def errors(self):
2103 return None
2104
2105 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002106 def encoding(self):
2107 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002108
2109 def detach(self):
2110 # This doesn't make sense on StringIO.
2111 self._unsupported("detach")