blob: d4cfb6e1264a90c71437bbd469718f1beaa05d01 [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
27# defined in io.py. We don't use real inheritance though, because we don't
28# want to inherit the C implementations.
29
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
796 except AttributeError:
797 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 """
836 return memoryview(self._buffer)
837
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300838 def read(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000839 if self.closed:
840 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300841 if size is None:
842 size = -1
843 if size < 0:
844 size = len(self._buffer)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000845 if len(self._buffer) <= self._pos:
846 return b""
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300847 newpos = min(len(self._buffer), self._pos + size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000848 b = self._buffer[self._pos : newpos]
849 self._pos = newpos
850 return bytes(b)
851
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300852 def read1(self, size):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000853 """This is the same as read.
854 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300855 return self.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000856
857 def write(self, b):
858 if self.closed:
859 raise ValueError("write to closed file")
860 if isinstance(b, str):
861 raise TypeError("can't write str to binary stream")
862 n = len(b)
863 if n == 0:
864 return 0
865 pos = self._pos
866 if pos > len(self._buffer):
867 # Inserts null bytes between the current end of the file
868 # and the new write position.
869 padding = b'\x00' * (pos - len(self._buffer))
870 self._buffer += padding
871 self._buffer[pos:pos + n] = b
872 self._pos += n
873 return n
874
875 def seek(self, pos, whence=0):
876 if self.closed:
877 raise ValueError("seek on closed file")
878 try:
Florent Xiclunab14930c2010-03-13 15:26:44 +0000879 pos.__index__
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000880 except AttributeError as err:
881 raise TypeError("an integer is required") from err
882 if whence == 0:
883 if pos < 0:
884 raise ValueError("negative seek position %r" % (pos,))
885 self._pos = pos
886 elif whence == 1:
887 self._pos = max(0, self._pos + pos)
888 elif whence == 2:
889 self._pos = max(0, len(self._buffer) + pos)
890 else:
Jesus Cea94363612012-06-22 18:32:07 +0200891 raise ValueError("unsupported whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000892 return self._pos
893
894 def tell(self):
895 if self.closed:
896 raise ValueError("tell on closed file")
897 return self._pos
898
899 def truncate(self, pos=None):
900 if self.closed:
901 raise ValueError("truncate on closed file")
902 if pos is None:
903 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000904 else:
905 try:
906 pos.__index__
907 except AttributeError as err:
908 raise TypeError("an integer is required") from err
909 if pos < 0:
910 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000911 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000912 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000913
914 def readable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200915 if self.closed:
916 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000917 return True
918
919 def writable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200920 if self.closed:
921 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000922 return True
923
924 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200925 if self.closed:
926 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000927 return True
928
929
930class BufferedReader(_BufferedIOMixin):
931
932 """BufferedReader(raw[, buffer_size])
933
934 A buffer for a readable, sequential BaseRawIO object.
935
936 The constructor creates a BufferedReader for the given readable raw
937 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
938 is used.
939 """
940
941 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
942 """Create a new buffered reader using the given readable raw IO object.
943 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000944 if not raw.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200945 raise OSError('"raw" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000946
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000947 _BufferedIOMixin.__init__(self, raw)
948 if buffer_size <= 0:
949 raise ValueError("invalid buffer size")
950 self.buffer_size = buffer_size
951 self._reset_read_buf()
952 self._read_lock = Lock()
953
954 def _reset_read_buf(self):
955 self._read_buf = b""
956 self._read_pos = 0
957
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300958 def read(self, size=None):
959 """Read size bytes.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000960
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300961 Returns exactly size bytes of data unless the underlying raw IO
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000962 stream reaches EOF or if the call would block in non-blocking
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300963 mode. If size is negative, read until EOF or until read() would
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000964 block.
965 """
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300966 if size is not None and size < -1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000967 raise ValueError("invalid number of bytes to read")
968 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300969 return self._read_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000970
971 def _read_unlocked(self, n=None):
972 nodata_val = b""
973 empty_values = (b"", None)
974 buf = self._read_buf
975 pos = self._read_pos
976
977 # Special case for when the number of bytes to read is unspecified.
978 if n is None or n == -1:
979 self._reset_read_buf()
Victor Stinnerb57f1082011-05-26 00:19:38 +0200980 if hasattr(self.raw, 'readall'):
981 chunk = self.raw.readall()
982 if chunk is None:
983 return buf[pos:] or None
984 else:
985 return buf[pos:] + chunk
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000986 chunks = [buf[pos:]] # Strip the consumed bytes.
987 current_size = 0
988 while True:
989 # Read until EOF or until read() would block.
Antoine Pitrou707ce822011-02-25 21:24:11 +0000990 try:
991 chunk = self.raw.read()
Antoine Pitrou24d659d2011-10-23 23:49:42 +0200992 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +0000993 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000994 if chunk in empty_values:
995 nodata_val = chunk
996 break
997 current_size += len(chunk)
998 chunks.append(chunk)
999 return b"".join(chunks) or nodata_val
1000
1001 # The number of bytes to read is specified, return at most n bytes.
1002 avail = len(buf) - pos # Length of the available buffered data.
1003 if n <= avail:
1004 # Fast path: the data to read is fully buffered.
1005 self._read_pos += n
1006 return buf[pos:pos+n]
1007 # Slow path: read from the stream until enough bytes are read,
1008 # or until an EOF occurs or until read() would block.
1009 chunks = [buf[pos:]]
1010 wanted = max(self.buffer_size, n)
1011 while avail < n:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001012 try:
1013 chunk = self.raw.read(wanted)
Antoine Pitrou24d659d2011-10-23 23:49:42 +02001014 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001015 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001016 if chunk in empty_values:
1017 nodata_val = chunk
1018 break
1019 avail += len(chunk)
1020 chunks.append(chunk)
1021 # n is more then avail only when an EOF occurred or when
1022 # read() would have blocked.
1023 n = min(n, avail)
1024 out = b"".join(chunks)
1025 self._read_buf = out[n:] # Save the extra data in the buffer.
1026 self._read_pos = 0
1027 return out[:n] if out else nodata_val
1028
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001029 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001030 """Returns buffered bytes without advancing the position.
1031
1032 The argument indicates a desired minimal number of bytes; we
1033 do at most one raw read to satisfy it. We never return more
1034 than self.buffer_size.
1035 """
1036 with self._read_lock:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001037 return self._peek_unlocked(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001038
1039 def _peek_unlocked(self, n=0):
1040 want = min(n, self.buffer_size)
1041 have = len(self._read_buf) - self._read_pos
1042 if have < want or have <= 0:
1043 to_read = self.buffer_size - have
Antoine Pitrou707ce822011-02-25 21:24:11 +00001044 while True:
1045 try:
1046 current = self.raw.read(to_read)
Antoine Pitrou24d659d2011-10-23 23:49:42 +02001047 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001048 continue
1049 break
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001050 if current:
1051 self._read_buf = self._read_buf[self._read_pos:] + current
1052 self._read_pos = 0
1053 return self._read_buf[self._read_pos:]
1054
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001055 def read1(self, size):
1056 """Reads up to size bytes, with at most one read() system call."""
1057 # Returns up to size bytes. If at least one byte is buffered, we
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001058 # only return buffered bytes. Otherwise, we do one raw read.
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001059 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001060 raise ValueError("number of bytes to read must be positive")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001061 if size == 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001062 return b""
1063 with self._read_lock:
1064 self._peek_unlocked(1)
1065 return self._read_unlocked(
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001066 min(size, len(self._read_buf) - self._read_pos))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001067
1068 def tell(self):
1069 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1070
1071 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001072 if whence not in valid_seek_flags:
Jesus Cea990eff02012-04-26 17:05:31 +02001073 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001074 with self._read_lock:
1075 if whence == 1:
1076 pos -= len(self._read_buf) - self._read_pos
1077 pos = _BufferedIOMixin.seek(self, pos, whence)
1078 self._reset_read_buf()
1079 return pos
1080
1081class BufferedWriter(_BufferedIOMixin):
1082
1083 """A buffer for a writeable sequential RawIO object.
1084
1085 The constructor creates a BufferedWriter for the given writeable raw
1086 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001087 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001088 """
1089
Florent Xicluna109d5732012-07-07 17:03:22 +02001090 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001091 if not raw.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001092 raise OSError('"raw" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001093
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001094 _BufferedIOMixin.__init__(self, raw)
1095 if buffer_size <= 0:
1096 raise ValueError("invalid buffer size")
1097 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001098 self._write_buf = bytearray()
1099 self._write_lock = Lock()
1100
1101 def write(self, b):
1102 if self.closed:
1103 raise ValueError("write to closed file")
1104 if isinstance(b, str):
1105 raise TypeError("can't write str to binary stream")
1106 with self._write_lock:
1107 # XXX we can implement some more tricks to try and avoid
1108 # partial writes
1109 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001110 # We're full, so let's pre-flush the buffer. (This may
1111 # raise BlockingIOError with characters_written == 0.)
1112 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001113 before = len(self._write_buf)
1114 self._write_buf.extend(b)
1115 written = len(self._write_buf) - before
1116 if len(self._write_buf) > self.buffer_size:
1117 try:
1118 self._flush_unlocked()
1119 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001120 if len(self._write_buf) > self.buffer_size:
1121 # We've hit the buffer_size. We have to accept a partial
1122 # write and cut back our buffer.
1123 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001124 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001125 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001126 raise BlockingIOError(e.errno, e.strerror, written)
1127 return written
1128
1129 def truncate(self, pos=None):
1130 with self._write_lock:
1131 self._flush_unlocked()
1132 if pos is None:
1133 pos = self.raw.tell()
1134 return self.raw.truncate(pos)
1135
1136 def flush(self):
1137 with self._write_lock:
1138 self._flush_unlocked()
1139
1140 def _flush_unlocked(self):
1141 if self.closed:
1142 raise ValueError("flush of closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001143 while self._write_buf:
1144 try:
1145 n = self.raw.write(self._write_buf)
Antoine Pitrou7fe601c2011-11-21 20:22:01 +01001146 except InterruptedError:
1147 continue
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001148 except BlockingIOError:
1149 raise RuntimeError("self.raw should implement RawIOBase: it "
1150 "should not raise BlockingIOError")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001151 if n is None:
1152 raise BlockingIOError(
1153 errno.EAGAIN,
1154 "write could not complete without blocking", 0)
1155 if n > len(self._write_buf) or n < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001156 raise OSError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001157 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001158
1159 def tell(self):
1160 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1161
1162 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001163 if whence not in valid_seek_flags:
1164 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001165 with self._write_lock:
1166 self._flush_unlocked()
1167 return _BufferedIOMixin.seek(self, pos, whence)
1168
1169
1170class BufferedRWPair(BufferedIOBase):
1171
1172 """A buffered reader and writer object together.
1173
1174 A buffered reader object and buffered writer object put together to
1175 form a sequential IO object that can read and write. This is typically
1176 used with a socket or two-way pipe.
1177
1178 reader and writer are RawIOBase objects that are readable and
1179 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001180 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001181 """
1182
1183 # XXX The usefulness of this (compared to having two separate IO
1184 # objects) is questionable.
1185
Florent Xicluna109d5732012-07-07 17:03:22 +02001186 def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001187 """Constructor.
1188
1189 The arguments are two RawIO instances.
1190 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001191 if not reader.readable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001192 raise OSError('"reader" argument must be readable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001193
1194 if not writer.writable():
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001195 raise OSError('"writer" argument must be writable.')
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001196
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001197 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001198 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001199
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001200 def read(self, size=None):
1201 if size is None:
1202 size = -1
1203 return self.reader.read(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001204
1205 def readinto(self, b):
1206 return self.reader.readinto(b)
1207
1208 def write(self, b):
1209 return self.writer.write(b)
1210
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001211 def peek(self, size=0):
1212 return self.reader.peek(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001213
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001214 def read1(self, size):
1215 return self.reader.read1(size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001216
1217 def readable(self):
1218 return self.reader.readable()
1219
1220 def writable(self):
1221 return self.writer.writable()
1222
1223 def flush(self):
1224 return self.writer.flush()
1225
1226 def close(self):
1227 self.writer.close()
1228 self.reader.close()
1229
1230 def isatty(self):
1231 return self.reader.isatty() or self.writer.isatty()
1232
1233 @property
1234 def closed(self):
1235 return self.writer.closed
1236
1237
1238class BufferedRandom(BufferedWriter, BufferedReader):
1239
1240 """A buffered interface to random access streams.
1241
1242 The constructor creates a reader and writer for a seekable stream,
1243 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001244 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001245 """
1246
Florent Xicluna109d5732012-07-07 17:03:22 +02001247 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001248 raw._checkSeekable()
1249 BufferedReader.__init__(self, raw, buffer_size)
Florent Xicluna109d5732012-07-07 17:03:22 +02001250 BufferedWriter.__init__(self, raw, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001251
1252 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001253 if whence not in valid_seek_flags:
1254 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001255 self.flush()
1256 if self._read_buf:
1257 # Undo read ahead.
1258 with self._read_lock:
1259 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1260 # First do the raw seek, then empty the read buffer, so that
1261 # if the raw seek fails, we don't lose buffered data forever.
1262 pos = self.raw.seek(pos, whence)
1263 with self._read_lock:
1264 self._reset_read_buf()
1265 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001266 raise OSError("seek() returned invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001267 return pos
1268
1269 def tell(self):
1270 if self._write_buf:
1271 return BufferedWriter.tell(self)
1272 else:
1273 return BufferedReader.tell(self)
1274
1275 def truncate(self, pos=None):
1276 if pos is None:
1277 pos = self.tell()
1278 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001279 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001280
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001281 def read(self, size=None):
1282 if size is None:
1283 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001284 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001285 return BufferedReader.read(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001286
1287 def readinto(self, b):
1288 self.flush()
1289 return BufferedReader.readinto(self, b)
1290
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001291 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001292 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001293 return BufferedReader.peek(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001294
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001295 def read1(self, size):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001296 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001297 return BufferedReader.read1(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001298
1299 def write(self, b):
1300 if self._read_buf:
1301 # Undo readahead
1302 with self._read_lock:
1303 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1304 self._reset_read_buf()
1305 return BufferedWriter.write(self, b)
1306
1307
1308class TextIOBase(IOBase):
1309
1310 """Base class for text I/O.
1311
1312 This class provides a character and line based interface to stream
1313 I/O. There is no readinto method because Python's character strings
1314 are immutable. There is no public constructor.
1315 """
1316
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001317 def read(self, size=-1):
1318 """Read at most size characters from stream, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001319
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001320 Read from underlying buffer until we have size characters or we hit EOF.
1321 If size is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001322
1323 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001324 """
1325 self._unsupported("read")
1326
Raymond Hettinger3c940242011-01-12 23:39:31 +00001327 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001328 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001329 self._unsupported("write")
1330
Georg Brandl4d73b572011-01-13 07:13:06 +00001331 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001332 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001333 self._unsupported("truncate")
1334
Raymond Hettinger3c940242011-01-12 23:39:31 +00001335 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001336 """Read until newline or EOF.
1337
1338 Returns an empty string if EOF is hit immediately.
1339 """
1340 self._unsupported("readline")
1341
Raymond Hettinger3c940242011-01-12 23:39:31 +00001342 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001343 """
1344 Separate the underlying buffer from the TextIOBase and return it.
1345
1346 After the underlying buffer has been detached, the TextIO is in an
1347 unusable state.
1348 """
1349 self._unsupported("detach")
1350
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001351 @property
1352 def encoding(self):
1353 """Subclasses should override."""
1354 return None
1355
1356 @property
1357 def newlines(self):
1358 """Line endings translated so far.
1359
1360 Only line endings translated during reading are considered.
1361
1362 Subclasses should override.
1363 """
1364 return None
1365
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001366 @property
1367 def errors(self):
1368 """Error setting of the decoder or encoder.
1369
1370 Subclasses should override."""
1371 return None
1372
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001373io.TextIOBase.register(TextIOBase)
1374
1375
1376class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1377 r"""Codec used when reading a file in universal newlines mode. It wraps
1378 another incremental decoder, translating \r\n and \r into \n. It also
1379 records the types of newlines encountered. When used with
1380 translate=False, it ensures that the newline sequence is returned in
1381 one piece.
1382 """
1383 def __init__(self, decoder, translate, errors='strict'):
1384 codecs.IncrementalDecoder.__init__(self, errors=errors)
1385 self.translate = translate
1386 self.decoder = decoder
1387 self.seennl = 0
1388 self.pendingcr = False
1389
1390 def decode(self, input, final=False):
1391 # decode input (with the eventual \r from a previous pass)
1392 if self.decoder is None:
1393 output = input
1394 else:
1395 output = self.decoder.decode(input, final=final)
1396 if self.pendingcr and (output or final):
1397 output = "\r" + output
1398 self.pendingcr = False
1399
1400 # retain last \r even when not translating data:
1401 # then readline() is sure to get \r\n in one pass
1402 if output.endswith("\r") and not final:
1403 output = output[:-1]
1404 self.pendingcr = True
1405
1406 # Record which newlines are read
1407 crlf = output.count('\r\n')
1408 cr = output.count('\r') - crlf
1409 lf = output.count('\n') - crlf
1410 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1411 | (crlf and self._CRLF)
1412
1413 if self.translate:
1414 if crlf:
1415 output = output.replace("\r\n", "\n")
1416 if cr:
1417 output = output.replace("\r", "\n")
1418
1419 return output
1420
1421 def getstate(self):
1422 if self.decoder is None:
1423 buf = b""
1424 flag = 0
1425 else:
1426 buf, flag = self.decoder.getstate()
1427 flag <<= 1
1428 if self.pendingcr:
1429 flag |= 1
1430 return buf, flag
1431
1432 def setstate(self, state):
1433 buf, flag = state
1434 self.pendingcr = bool(flag & 1)
1435 if self.decoder is not None:
1436 self.decoder.setstate((buf, flag >> 1))
1437
1438 def reset(self):
1439 self.seennl = 0
1440 self.pendingcr = False
1441 if self.decoder is not None:
1442 self.decoder.reset()
1443
1444 _LF = 1
1445 _CR = 2
1446 _CRLF = 4
1447
1448 @property
1449 def newlines(self):
1450 return (None,
1451 "\n",
1452 "\r",
1453 ("\r", "\n"),
1454 "\r\n",
1455 ("\n", "\r\n"),
1456 ("\r", "\r\n"),
1457 ("\r", "\n", "\r\n")
1458 )[self.seennl]
1459
1460
1461class TextIOWrapper(TextIOBase):
1462
1463 r"""Character and line based layer over a BufferedIOBase object, buffer.
1464
1465 encoding gives the name of the encoding that the stream will be
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001466 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001467
1468 errors determines the strictness of encoding and decoding (see the
1469 codecs.register) and defaults to "strict".
1470
1471 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1472 handling of line endings. If it is None, universal newlines is
1473 enabled. With this enabled, on input, the lines endings '\n', '\r',
1474 or '\r\n' are translated to '\n' before being returned to the
1475 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001476 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001477 legal values, that newline becomes the newline when the file is read
1478 and it is returned untranslated. On output, '\n' is converted to the
1479 newline.
1480
1481 If line_buffering is True, a call to flush is implied when a call to
1482 write contains a newline character.
1483 """
1484
1485 _CHUNK_SIZE = 2048
1486
Andrew Svetlov4e9e9c12012-08-13 16:09:54 +03001487 # The write_through argument has no effect here since this
1488 # implementation always writes through. The argument is present only
1489 # so that the signature can match the signature of the C version.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001490 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001491 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001492 if newline is not None and not isinstance(newline, str):
1493 raise TypeError("illegal newline type: %r" % (type(newline),))
1494 if newline not in (None, "", "\n", "\r", "\r\n"):
1495 raise ValueError("illegal newline value: %r" % (newline,))
1496 if encoding is None:
1497 try:
1498 encoding = os.device_encoding(buffer.fileno())
1499 except (AttributeError, UnsupportedOperation):
1500 pass
1501 if encoding is None:
1502 try:
1503 import locale
Brett Cannoncd171c82013-07-04 17:43:24 -04001504 except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001505 # Importing locale may fail if Python is being built
1506 encoding = "ascii"
1507 else:
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001508 encoding = locale.getpreferredencoding(False)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001509
1510 if not isinstance(encoding, str):
1511 raise ValueError("invalid encoding: %r" % encoding)
1512
Nick Coghlana9b15242014-02-04 22:11:18 +10001513 if not codecs.lookup(encoding)._is_text_encoding:
1514 msg = ("%r is not a text encoding; "
1515 "use codecs.open() to handle arbitrary codecs")
1516 raise LookupError(msg % encoding)
1517
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001518 if errors is None:
1519 errors = "strict"
1520 else:
1521 if not isinstance(errors, str):
1522 raise ValueError("invalid errors: %r" % errors)
1523
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001524 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001525 self._line_buffering = line_buffering
1526 self._encoding = encoding
1527 self._errors = errors
1528 self._readuniversal = not newline
1529 self._readtranslate = newline is None
1530 self._readnl = newline
1531 self._writetranslate = newline != ''
1532 self._writenl = newline or os.linesep
1533 self._encoder = None
1534 self._decoder = None
1535 self._decoded_chars = '' # buffer for text returned from decoder
1536 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1537 self._snapshot = None # info for reconstructing decoder state
1538 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001539 self._has_read1 = hasattr(self.buffer, 'read1')
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001540 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001541
Antoine Pitroue4501852009-05-14 18:55:55 +00001542 if self._seekable and self.writable():
1543 position = self.buffer.tell()
1544 if position != 0:
1545 try:
1546 self._get_encoder().setstate(0)
1547 except LookupError:
1548 # Sometimes the encoder doesn't exist
1549 pass
1550
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001551 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1552 # where dec_flags is the second (integer) item of the decoder state
1553 # and next_input is the chunk of input bytes that comes next after the
1554 # snapshot point. We use this to reconstruct decoder states in tell().
1555
1556 # Naming convention:
1557 # - "bytes_..." for integer variables that count input bytes
1558 # - "chars_..." for integer variables that count decoded characters
1559
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001560 def __repr__(self):
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001561 result = "<_pyio.TextIOWrapper"
Antoine Pitrou716c4442009-05-23 19:04:03 +00001562 try:
1563 name = self.name
1564 except AttributeError:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001565 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00001566 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001567 result += " name={0!r}".format(name)
1568 try:
1569 mode = self.mode
1570 except AttributeError:
1571 pass
1572 else:
1573 result += " mode={0!r}".format(mode)
1574 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001575
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001576 @property
1577 def encoding(self):
1578 return self._encoding
1579
1580 @property
1581 def errors(self):
1582 return self._errors
1583
1584 @property
1585 def line_buffering(self):
1586 return self._line_buffering
1587
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001588 @property
1589 def buffer(self):
1590 return self._buffer
1591
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001592 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02001593 if self.closed:
1594 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001595 return self._seekable
1596
1597 def readable(self):
1598 return self.buffer.readable()
1599
1600 def writable(self):
1601 return self.buffer.writable()
1602
1603 def flush(self):
1604 self.buffer.flush()
1605 self._telling = self._seekable
1606
1607 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00001608 if self.buffer is not None and not self.closed:
Benjamin Peterson68623612012-12-20 11:53:11 -06001609 try:
1610 self.flush()
1611 finally:
1612 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001613
1614 @property
1615 def closed(self):
1616 return self.buffer.closed
1617
1618 @property
1619 def name(self):
1620 return self.buffer.name
1621
1622 def fileno(self):
1623 return self.buffer.fileno()
1624
1625 def isatty(self):
1626 return self.buffer.isatty()
1627
Raymond Hettinger00fa0392011-01-13 02:52:26 +00001628 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001629 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001630 if self.closed:
1631 raise ValueError("write to closed file")
1632 if not isinstance(s, str):
1633 raise TypeError("can't write %s to text stream" %
1634 s.__class__.__name__)
1635 length = len(s)
1636 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1637 if haslf and self._writetranslate and self._writenl != "\n":
1638 s = s.replace("\n", self._writenl)
1639 encoder = self._encoder or self._get_encoder()
1640 # XXX What if we were just reading?
1641 b = encoder.encode(s)
1642 self.buffer.write(b)
1643 if self._line_buffering and (haslf or "\r" in s):
1644 self.flush()
1645 self._snapshot = None
1646 if self._decoder:
1647 self._decoder.reset()
1648 return length
1649
1650 def _get_encoder(self):
1651 make_encoder = codecs.getincrementalencoder(self._encoding)
1652 self._encoder = make_encoder(self._errors)
1653 return self._encoder
1654
1655 def _get_decoder(self):
1656 make_decoder = codecs.getincrementaldecoder(self._encoding)
1657 decoder = make_decoder(self._errors)
1658 if self._readuniversal:
1659 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1660 self._decoder = decoder
1661 return decoder
1662
1663 # The following three methods implement an ADT for _decoded_chars.
1664 # Text returned from the decoder is buffered here until the client
1665 # requests it by calling our read() or readline() method.
1666 def _set_decoded_chars(self, chars):
1667 """Set the _decoded_chars buffer."""
1668 self._decoded_chars = chars
1669 self._decoded_chars_used = 0
1670
1671 def _get_decoded_chars(self, n=None):
1672 """Advance into the _decoded_chars buffer."""
1673 offset = self._decoded_chars_used
1674 if n is None:
1675 chars = self._decoded_chars[offset:]
1676 else:
1677 chars = self._decoded_chars[offset:offset + n]
1678 self._decoded_chars_used += len(chars)
1679 return chars
1680
1681 def _rewind_decoded_chars(self, n):
1682 """Rewind the _decoded_chars buffer."""
1683 if self._decoded_chars_used < n:
1684 raise AssertionError("rewind decoded_chars out of bounds")
1685 self._decoded_chars_used -= n
1686
1687 def _read_chunk(self):
1688 """
1689 Read and decode the next chunk of data from the BufferedReader.
1690 """
1691
1692 # The return value is True unless EOF was reached. The decoded
1693 # string is placed in self._decoded_chars (replacing its previous
1694 # value). The entire input chunk is sent to the decoder, though
1695 # some of it may remain buffered in the decoder, yet to be
1696 # converted.
1697
1698 if self._decoder is None:
1699 raise ValueError("no decoder")
1700
1701 if self._telling:
1702 # To prepare for tell(), we need to snapshot a point in the
1703 # file where the decoder's input buffer is empty.
1704
1705 dec_buffer, dec_flags = self._decoder.getstate()
1706 # Given this, we know there was a valid snapshot point
1707 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1708
1709 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02001710 if self._has_read1:
1711 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1712 else:
1713 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001714 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001715 decoded_chars = self._decoder.decode(input_chunk, eof)
1716 self._set_decoded_chars(decoded_chars)
1717 if decoded_chars:
1718 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
1719 else:
1720 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001721
1722 if self._telling:
1723 # At the snapshot point, len(dec_buffer) bytes before the read,
1724 # the next input to be decoded is dec_buffer + input_chunk.
1725 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1726
1727 return not eof
1728
1729 def _pack_cookie(self, position, dec_flags=0,
1730 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1731 # The meaning of a tell() cookie is: seek to position, set the
1732 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1733 # into the decoder with need_eof as the EOF flag, then skip
1734 # chars_to_skip characters of the decoded result. For most simple
1735 # decoders, tell() will often just give a byte offset in the file.
1736 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1737 (chars_to_skip<<192) | bool(need_eof)<<256)
1738
1739 def _unpack_cookie(self, bigint):
1740 rest, position = divmod(bigint, 1<<64)
1741 rest, dec_flags = divmod(rest, 1<<64)
1742 rest, bytes_to_feed = divmod(rest, 1<<64)
1743 need_eof, chars_to_skip = divmod(rest, 1<<64)
1744 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1745
1746 def tell(self):
1747 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001748 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001749 if not self._telling:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001750 raise OSError("telling position disabled by next() call")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001751 self.flush()
1752 position = self.buffer.tell()
1753 decoder = self._decoder
1754 if decoder is None or self._snapshot is None:
1755 if self._decoded_chars:
1756 # This should never happen.
1757 raise AssertionError("pending decoded text")
1758 return position
1759
1760 # Skip backward to the snapshot point (see _read_chunk).
1761 dec_flags, next_input = self._snapshot
1762 position -= len(next_input)
1763
1764 # How many decoded characters have been used up since the snapshot?
1765 chars_to_skip = self._decoded_chars_used
1766 if chars_to_skip == 0:
1767 # We haven't moved from the snapshot point.
1768 return self._pack_cookie(position, dec_flags)
1769
1770 # Starting from the snapshot position, we will walk the decoder
1771 # forward until it gives us enough decoded characters.
1772 saved_state = decoder.getstate()
1773 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001774 # Fast search for an acceptable start point, close to our
1775 # current pos.
1776 # Rationale: calling decoder.decode() has a large overhead
1777 # regardless of chunk size; we want the number of such calls to
1778 # be O(1) in most situations (common decoders, non-crazy input).
1779 # Actually, it will be exactly 1 for fixed-size codecs (all
1780 # 8-bit codecs, also UTF-16 and UTF-32).
1781 skip_bytes = int(self._b2cratio * chars_to_skip)
1782 skip_back = 1
1783 assert skip_bytes <= len(next_input)
1784 while skip_bytes > 0:
1785 decoder.setstate((b'', dec_flags))
1786 # Decode up to temptative start point
1787 n = len(decoder.decode(next_input[:skip_bytes]))
1788 if n <= chars_to_skip:
1789 b, d = decoder.getstate()
1790 if not b:
1791 # Before pos and no bytes buffered in decoder => OK
1792 dec_flags = d
1793 chars_to_skip -= n
1794 break
1795 # Skip back by buffered amount and reset heuristic
1796 skip_bytes -= len(b)
1797 skip_back = 1
1798 else:
1799 # We're too far ahead, skip back a bit
1800 skip_bytes -= skip_back
1801 skip_back = skip_back * 2
1802 else:
1803 skip_bytes = 0
1804 decoder.setstate((b'', dec_flags))
1805
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001806 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001807 start_pos = position + skip_bytes
1808 start_flags = dec_flags
1809 if chars_to_skip == 0:
1810 # We haven't moved from the start point.
1811 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001812
1813 # Feed the decoder one byte at a time. As we go, note the
1814 # nearest "safe start point" before the current location
1815 # (a point where the decoder has nothing buffered, so seek()
1816 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001817 bytes_fed = 0
1818 need_eof = 0
1819 # Chars decoded since `start_pos`
1820 chars_decoded = 0
1821 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001822 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001823 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001824 dec_buffer, dec_flags = decoder.getstate()
1825 if not dec_buffer and chars_decoded <= chars_to_skip:
1826 # Decoder buffer is empty, so this is a safe start point.
1827 start_pos += bytes_fed
1828 chars_to_skip -= chars_decoded
1829 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1830 if chars_decoded >= chars_to_skip:
1831 break
1832 else:
1833 # We didn't get enough decoded data; signal EOF to get more.
1834 chars_decoded += len(decoder.decode(b'', final=True))
1835 need_eof = 1
1836 if chars_decoded < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001837 raise OSError("can't reconstruct logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001838
1839 # The returned cookie corresponds to the last safe start point.
1840 return self._pack_cookie(
1841 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1842 finally:
1843 decoder.setstate(saved_state)
1844
1845 def truncate(self, pos=None):
1846 self.flush()
1847 if pos is None:
1848 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001849 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001850
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001851 def detach(self):
1852 if self.buffer is None:
1853 raise ValueError("buffer is already detached")
1854 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001855 buffer = self._buffer
1856 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001857 return buffer
1858
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001859 def seek(self, cookie, whence=0):
1860 if self.closed:
1861 raise ValueError("tell on closed file")
1862 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001863 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001864 if whence == 1: # seek relative to current position
1865 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001866 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001867 # Seeking to the current position should attempt to
1868 # sync the underlying buffer with the current position.
1869 whence = 0
1870 cookie = self.tell()
1871 if whence == 2: # seek relative to end of file
1872 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001873 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001874 self.flush()
1875 position = self.buffer.seek(0, 2)
1876 self._set_decoded_chars('')
1877 self._snapshot = None
1878 if self._decoder:
1879 self._decoder.reset()
1880 return position
1881 if whence != 0:
Jesus Cea94363612012-06-22 18:32:07 +02001882 raise ValueError("unsupported whence (%r)" % (whence,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001883 if cookie < 0:
1884 raise ValueError("negative seek position %r" % (cookie,))
1885 self.flush()
1886
1887 # The strategy of seek() is to go back to the safe start point
1888 # and replay the effect of read(chars_to_skip) from there.
1889 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1890 self._unpack_cookie(cookie)
1891
1892 # Seek back to the safe start point.
1893 self.buffer.seek(start_pos)
1894 self._set_decoded_chars('')
1895 self._snapshot = None
1896
1897 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001898 if cookie == 0 and self._decoder:
1899 self._decoder.reset()
1900 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001901 self._decoder = self._decoder or self._get_decoder()
1902 self._decoder.setstate((b'', dec_flags))
1903 self._snapshot = (dec_flags, b'')
1904
1905 if chars_to_skip:
1906 # Just like _read_chunk, feed the decoder and save a snapshot.
1907 input_chunk = self.buffer.read(bytes_to_feed)
1908 self._set_decoded_chars(
1909 self._decoder.decode(input_chunk, need_eof))
1910 self._snapshot = (dec_flags, input_chunk)
1911
1912 # Skip chars_to_skip of the decoded characters.
1913 if len(self._decoded_chars) < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001914 raise OSError("can't restore logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001915 self._decoded_chars_used = chars_to_skip
1916
Antoine Pitroue4501852009-05-14 18:55:55 +00001917 # Finally, reset the encoder (merely useful for proper BOM handling)
1918 try:
1919 encoder = self._encoder or self._get_encoder()
1920 except LookupError:
1921 # Sometimes the encoder doesn't exist
1922 pass
1923 else:
1924 if cookie != 0:
1925 encoder.setstate(0)
1926 else:
1927 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001928 return cookie
1929
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001930 def read(self, size=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00001931 self._checkReadable()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001932 if size is None:
1933 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001934 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00001935 try:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001936 size.__index__
Florent Xiclunab14930c2010-03-13 15:26:44 +00001937 except AttributeError as err:
1938 raise TypeError("an integer is required") from err
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001939 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001940 # Read everything.
1941 result = (self._get_decoded_chars() +
1942 decoder.decode(self.buffer.read(), final=True))
1943 self._set_decoded_chars('')
1944 self._snapshot = None
1945 return result
1946 else:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001947 # Keep reading chunks until we have size characters to return.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001948 eof = False
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001949 result = self._get_decoded_chars(size)
1950 while len(result) < size and not eof:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001951 eof = not self._read_chunk()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001952 result += self._get_decoded_chars(size - len(result))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001953 return result
1954
1955 def __next__(self):
1956 self._telling = False
1957 line = self.readline()
1958 if not line:
1959 self._snapshot = None
1960 self._telling = self._seekable
1961 raise StopIteration
1962 return line
1963
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001964 def readline(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001965 if self.closed:
1966 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001967 if size is None:
1968 size = -1
1969 elif not isinstance(size, int):
1970 raise TypeError("size must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001971
1972 # Grab all the decoded text (we will rewind any extra bits later).
1973 line = self._get_decoded_chars()
1974
1975 start = 0
1976 # Make the decoder if it doesn't already exist.
1977 if not self._decoder:
1978 self._get_decoder()
1979
1980 pos = endpos = None
1981 while True:
1982 if self._readtranslate:
1983 # Newlines are already translated, only search for \n
1984 pos = line.find('\n', start)
1985 if pos >= 0:
1986 endpos = pos + 1
1987 break
1988 else:
1989 start = len(line)
1990
1991 elif self._readuniversal:
1992 # Universal newline search. Find any of \r, \r\n, \n
1993 # The decoder ensures that \r\n are not split in two pieces
1994
1995 # In C we'd look for these in parallel of course.
1996 nlpos = line.find("\n", start)
1997 crpos = line.find("\r", start)
1998 if crpos == -1:
1999 if nlpos == -1:
2000 # Nothing found
2001 start = len(line)
2002 else:
2003 # Found \n
2004 endpos = nlpos + 1
2005 break
2006 elif nlpos == -1:
2007 # Found lone \r
2008 endpos = crpos + 1
2009 break
2010 elif nlpos < crpos:
2011 # Found \n
2012 endpos = nlpos + 1
2013 break
2014 elif nlpos == crpos + 1:
2015 # Found \r\n
2016 endpos = crpos + 2
2017 break
2018 else:
2019 # Found \r
2020 endpos = crpos + 1
2021 break
2022 else:
2023 # non-universal
2024 pos = line.find(self._readnl)
2025 if pos >= 0:
2026 endpos = pos + len(self._readnl)
2027 break
2028
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002029 if size >= 0 and len(line) >= size:
2030 endpos = size # reached length size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002031 break
2032
2033 # No line ending seen yet - get more data'
2034 while self._read_chunk():
2035 if self._decoded_chars:
2036 break
2037 if self._decoded_chars:
2038 line += self._get_decoded_chars()
2039 else:
2040 # end of file
2041 self._set_decoded_chars('')
2042 self._snapshot = None
2043 return line
2044
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002045 if size >= 0 and endpos > size:
2046 endpos = size # don't exceed size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002047
2048 # Rewind _decoded_chars to just after the line ending we found.
2049 self._rewind_decoded_chars(len(line) - endpos)
2050 return line[:endpos]
2051
2052 @property
2053 def newlines(self):
2054 return self._decoder.newlines if self._decoder else None
2055
2056
2057class StringIO(TextIOWrapper):
2058 """Text I/O implementation using an in-memory buffer.
2059
2060 The initial_value argument sets the value of object. The newline
2061 argument is like the one of TextIOWrapper's constructor.
2062 """
2063
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002064 def __init__(self, initial_value="", newline="\n"):
2065 super(StringIO, self).__init__(BytesIO(),
2066 encoding="utf-8",
Serhiy Storchakac92ea762014-01-29 11:33:26 +02002067 errors="surrogatepass",
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002068 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002069 # Issue #5645: make universal newlines semantics the same as in the
2070 # C version, even under Windows.
2071 if newline is None:
2072 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002073 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002074 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002075 raise TypeError("initial_value must be str or None, not {0}"
2076 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002077 self.write(initial_value)
2078 self.seek(0)
2079
2080 def getvalue(self):
2081 self.flush()
Antoine Pitrou57839a62014-02-02 23:37:29 +01002082 decoder = self._decoder or self._get_decoder()
2083 old_state = decoder.getstate()
2084 decoder.reset()
2085 try:
2086 return decoder.decode(self.buffer.getvalue(), final=True)
2087 finally:
2088 decoder.setstate(old_state)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002089
2090 def __repr__(self):
2091 # TextIOWrapper tells the encoding in its repr. In StringIO,
2092 # that's a implementation detail.
2093 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002094
2095 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002096 def errors(self):
2097 return None
2098
2099 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002100 def encoding(self):
2101 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002102
2103 def detach(self):
2104 # This doesn't make sense on StringIO.
2105 self._unsupported("detach")