blob: c0b5fd12af53491afc4a9f5b34b5be0976f70a83 [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):
Serhiy Storchaka7665be62015-03-24 23:21:57 +02001233 try:
1234 self.writer.close()
1235 finally:
1236 self.reader.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001237
1238 def isatty(self):
1239 return self.reader.isatty() or self.writer.isatty()
1240
1241 @property
1242 def closed(self):
1243 return self.writer.closed
1244
1245
1246class BufferedRandom(BufferedWriter, BufferedReader):
1247
1248 """A buffered interface to random access streams.
1249
1250 The constructor creates a reader and writer for a seekable stream,
1251 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001252 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001253 """
1254
Florent Xicluna109d5732012-07-07 17:03:22 +02001255 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001256 raw._checkSeekable()
1257 BufferedReader.__init__(self, raw, buffer_size)
Florent Xicluna109d5732012-07-07 17:03:22 +02001258 BufferedWriter.__init__(self, raw, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001259
1260 def seek(self, pos, whence=0):
Jesus Cea94363612012-06-22 18:32:07 +02001261 if whence not in valid_seek_flags:
1262 raise ValueError("invalid whence value")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001263 self.flush()
1264 if self._read_buf:
1265 # Undo read ahead.
1266 with self._read_lock:
1267 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1268 # First do the raw seek, then empty the read buffer, so that
1269 # if the raw seek fails, we don't lose buffered data forever.
1270 pos = self.raw.seek(pos, whence)
1271 with self._read_lock:
1272 self._reset_read_buf()
1273 if pos < 0:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001274 raise OSError("seek() returned invalid position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001275 return pos
1276
1277 def tell(self):
1278 if self._write_buf:
1279 return BufferedWriter.tell(self)
1280 else:
1281 return BufferedReader.tell(self)
1282
1283 def truncate(self, pos=None):
1284 if pos is None:
1285 pos = self.tell()
1286 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001287 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001288
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001289 def read(self, size=None):
1290 if size is None:
1291 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001292 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001293 return BufferedReader.read(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001294
1295 def readinto(self, b):
1296 self.flush()
1297 return BufferedReader.readinto(self, b)
1298
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001299 def peek(self, size=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001300 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001301 return BufferedReader.peek(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001302
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001303 def read1(self, size):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001304 self.flush()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001305 return BufferedReader.read1(self, size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001306
1307 def write(self, b):
1308 if self._read_buf:
1309 # Undo readahead
1310 with self._read_lock:
1311 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1312 self._reset_read_buf()
1313 return BufferedWriter.write(self, b)
1314
1315
1316class TextIOBase(IOBase):
1317
1318 """Base class for text I/O.
1319
1320 This class provides a character and line based interface to stream
1321 I/O. There is no readinto method because Python's character strings
1322 are immutable. There is no public constructor.
1323 """
1324
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001325 def read(self, size=-1):
1326 """Read at most size characters from stream, where size is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001327
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001328 Read from underlying buffer until we have size characters or we hit EOF.
1329 If size is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001330
1331 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001332 """
1333 self._unsupported("read")
1334
Raymond Hettinger3c940242011-01-12 23:39:31 +00001335 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001336 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001337 self._unsupported("write")
1338
Georg Brandl4d73b572011-01-13 07:13:06 +00001339 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001340 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001341 self._unsupported("truncate")
1342
Raymond Hettinger3c940242011-01-12 23:39:31 +00001343 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001344 """Read until newline or EOF.
1345
1346 Returns an empty string if EOF is hit immediately.
1347 """
1348 self._unsupported("readline")
1349
Raymond Hettinger3c940242011-01-12 23:39:31 +00001350 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001351 """
1352 Separate the underlying buffer from the TextIOBase and return it.
1353
1354 After the underlying buffer has been detached, the TextIO is in an
1355 unusable state.
1356 """
1357 self._unsupported("detach")
1358
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001359 @property
1360 def encoding(self):
1361 """Subclasses should override."""
1362 return None
1363
1364 @property
1365 def newlines(self):
1366 """Line endings translated so far.
1367
1368 Only line endings translated during reading are considered.
1369
1370 Subclasses should override.
1371 """
1372 return None
1373
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001374 @property
1375 def errors(self):
1376 """Error setting of the decoder or encoder.
1377
1378 Subclasses should override."""
1379 return None
1380
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001381io.TextIOBase.register(TextIOBase)
1382
1383
1384class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1385 r"""Codec used when reading a file in universal newlines mode. It wraps
1386 another incremental decoder, translating \r\n and \r into \n. It also
1387 records the types of newlines encountered. When used with
1388 translate=False, it ensures that the newline sequence is returned in
1389 one piece.
1390 """
1391 def __init__(self, decoder, translate, errors='strict'):
1392 codecs.IncrementalDecoder.__init__(self, errors=errors)
1393 self.translate = translate
1394 self.decoder = decoder
1395 self.seennl = 0
1396 self.pendingcr = False
1397
1398 def decode(self, input, final=False):
1399 # decode input (with the eventual \r from a previous pass)
1400 if self.decoder is None:
1401 output = input
1402 else:
1403 output = self.decoder.decode(input, final=final)
1404 if self.pendingcr and (output or final):
1405 output = "\r" + output
1406 self.pendingcr = False
1407
1408 # retain last \r even when not translating data:
1409 # then readline() is sure to get \r\n in one pass
1410 if output.endswith("\r") and not final:
1411 output = output[:-1]
1412 self.pendingcr = True
1413
1414 # Record which newlines are read
1415 crlf = output.count('\r\n')
1416 cr = output.count('\r') - crlf
1417 lf = output.count('\n') - crlf
1418 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1419 | (crlf and self._CRLF)
1420
1421 if self.translate:
1422 if crlf:
1423 output = output.replace("\r\n", "\n")
1424 if cr:
1425 output = output.replace("\r", "\n")
1426
1427 return output
1428
1429 def getstate(self):
1430 if self.decoder is None:
1431 buf = b""
1432 flag = 0
1433 else:
1434 buf, flag = self.decoder.getstate()
1435 flag <<= 1
1436 if self.pendingcr:
1437 flag |= 1
1438 return buf, flag
1439
1440 def setstate(self, state):
1441 buf, flag = state
1442 self.pendingcr = bool(flag & 1)
1443 if self.decoder is not None:
1444 self.decoder.setstate((buf, flag >> 1))
1445
1446 def reset(self):
1447 self.seennl = 0
1448 self.pendingcr = False
1449 if self.decoder is not None:
1450 self.decoder.reset()
1451
1452 _LF = 1
1453 _CR = 2
1454 _CRLF = 4
1455
1456 @property
1457 def newlines(self):
1458 return (None,
1459 "\n",
1460 "\r",
1461 ("\r", "\n"),
1462 "\r\n",
1463 ("\n", "\r\n"),
1464 ("\r", "\r\n"),
1465 ("\r", "\n", "\r\n")
1466 )[self.seennl]
1467
1468
1469class TextIOWrapper(TextIOBase):
1470
1471 r"""Character and line based layer over a BufferedIOBase object, buffer.
1472
1473 encoding gives the name of the encoding that the stream will be
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001474 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001475
1476 errors determines the strictness of encoding and decoding (see the
1477 codecs.register) and defaults to "strict".
1478
1479 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1480 handling of line endings. If it is None, universal newlines is
1481 enabled. With this enabled, on input, the lines endings '\n', '\r',
1482 or '\r\n' are translated to '\n' before being returned to the
1483 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001484 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001485 legal values, that newline becomes the newline when the file is read
1486 and it is returned untranslated. On output, '\n' is converted to the
1487 newline.
1488
1489 If line_buffering is True, a call to flush is implied when a call to
1490 write contains a newline character.
1491 """
1492
1493 _CHUNK_SIZE = 2048
1494
Andrew Svetlov4e9e9c12012-08-13 16:09:54 +03001495 # The write_through argument has no effect here since this
1496 # implementation always writes through. The argument is present only
1497 # so that the signature can match the signature of the C version.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001498 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001499 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001500 if newline is not None and not isinstance(newline, str):
1501 raise TypeError("illegal newline type: %r" % (type(newline),))
1502 if newline not in (None, "", "\n", "\r", "\r\n"):
1503 raise ValueError("illegal newline value: %r" % (newline,))
1504 if encoding is None:
1505 try:
1506 encoding = os.device_encoding(buffer.fileno())
1507 except (AttributeError, UnsupportedOperation):
1508 pass
1509 if encoding is None:
1510 try:
1511 import locale
Brett Cannoncd171c82013-07-04 17:43:24 -04001512 except ImportError:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001513 # Importing locale may fail if Python is being built
1514 encoding = "ascii"
1515 else:
Victor Stinnerf86a5e82012-06-05 13:43:22 +02001516 encoding = locale.getpreferredencoding(False)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001517
1518 if not isinstance(encoding, str):
1519 raise ValueError("invalid encoding: %r" % encoding)
1520
Nick Coghlana9b15242014-02-04 22:11:18 +10001521 if not codecs.lookup(encoding)._is_text_encoding:
1522 msg = ("%r is not a text encoding; "
1523 "use codecs.open() to handle arbitrary codecs")
1524 raise LookupError(msg % encoding)
1525
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001526 if errors is None:
1527 errors = "strict"
1528 else:
1529 if not isinstance(errors, str):
1530 raise ValueError("invalid errors: %r" % errors)
1531
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001532 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001533 self._line_buffering = line_buffering
1534 self._encoding = encoding
1535 self._errors = errors
1536 self._readuniversal = not newline
1537 self._readtranslate = newline is None
1538 self._readnl = newline
1539 self._writetranslate = newline != ''
1540 self._writenl = newline or os.linesep
1541 self._encoder = None
1542 self._decoder = None
1543 self._decoded_chars = '' # buffer for text returned from decoder
1544 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1545 self._snapshot = None # info for reconstructing decoder state
1546 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001547 self._has_read1 = hasattr(self.buffer, 'read1')
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001548 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001549
Antoine Pitroue4501852009-05-14 18:55:55 +00001550 if self._seekable and self.writable():
1551 position = self.buffer.tell()
1552 if position != 0:
1553 try:
1554 self._get_encoder().setstate(0)
1555 except LookupError:
1556 # Sometimes the encoder doesn't exist
1557 pass
1558
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001559 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1560 # where dec_flags is the second (integer) item of the decoder state
1561 # and next_input is the chunk of input bytes that comes next after the
1562 # snapshot point. We use this to reconstruct decoder states in tell().
1563
1564 # Naming convention:
1565 # - "bytes_..." for integer variables that count input bytes
1566 # - "chars_..." for integer variables that count decoded characters
1567
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001568 def __repr__(self):
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001569 result = "<_pyio.TextIOWrapper"
Antoine Pitrou716c4442009-05-23 19:04:03 +00001570 try:
1571 name = self.name
Benjamin Peterson10e76b62014-12-21 20:51:50 -06001572 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001573 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00001574 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001575 result += " name={0!r}".format(name)
1576 try:
1577 mode = self.mode
Benjamin Peterson10e76b62014-12-21 20:51:50 -06001578 except Exception:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001579 pass
1580 else:
1581 result += " mode={0!r}".format(mode)
1582 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001583
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001584 @property
1585 def encoding(self):
1586 return self._encoding
1587
1588 @property
1589 def errors(self):
1590 return self._errors
1591
1592 @property
1593 def line_buffering(self):
1594 return self._line_buffering
1595
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001596 @property
1597 def buffer(self):
1598 return self._buffer
1599
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001600 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02001601 if self.closed:
1602 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001603 return self._seekable
1604
1605 def readable(self):
1606 return self.buffer.readable()
1607
1608 def writable(self):
1609 return self.buffer.writable()
1610
1611 def flush(self):
1612 self.buffer.flush()
1613 self._telling = self._seekable
1614
1615 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00001616 if self.buffer is not None and not self.closed:
Benjamin Peterson68623612012-12-20 11:53:11 -06001617 try:
1618 self.flush()
1619 finally:
1620 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001621
1622 @property
1623 def closed(self):
1624 return self.buffer.closed
1625
1626 @property
1627 def name(self):
1628 return self.buffer.name
1629
1630 def fileno(self):
1631 return self.buffer.fileno()
1632
1633 def isatty(self):
1634 return self.buffer.isatty()
1635
Raymond Hettinger00fa0392011-01-13 02:52:26 +00001636 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001637 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001638 if self.closed:
1639 raise ValueError("write to closed file")
1640 if not isinstance(s, str):
1641 raise TypeError("can't write %s to text stream" %
1642 s.__class__.__name__)
1643 length = len(s)
1644 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1645 if haslf and self._writetranslate and self._writenl != "\n":
1646 s = s.replace("\n", self._writenl)
1647 encoder = self._encoder or self._get_encoder()
1648 # XXX What if we were just reading?
1649 b = encoder.encode(s)
1650 self.buffer.write(b)
1651 if self._line_buffering and (haslf or "\r" in s):
1652 self.flush()
1653 self._snapshot = None
1654 if self._decoder:
1655 self._decoder.reset()
1656 return length
1657
1658 def _get_encoder(self):
1659 make_encoder = codecs.getincrementalencoder(self._encoding)
1660 self._encoder = make_encoder(self._errors)
1661 return self._encoder
1662
1663 def _get_decoder(self):
1664 make_decoder = codecs.getincrementaldecoder(self._encoding)
1665 decoder = make_decoder(self._errors)
1666 if self._readuniversal:
1667 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1668 self._decoder = decoder
1669 return decoder
1670
1671 # The following three methods implement an ADT for _decoded_chars.
1672 # Text returned from the decoder is buffered here until the client
1673 # requests it by calling our read() or readline() method.
1674 def _set_decoded_chars(self, chars):
1675 """Set the _decoded_chars buffer."""
1676 self._decoded_chars = chars
1677 self._decoded_chars_used = 0
1678
1679 def _get_decoded_chars(self, n=None):
1680 """Advance into the _decoded_chars buffer."""
1681 offset = self._decoded_chars_used
1682 if n is None:
1683 chars = self._decoded_chars[offset:]
1684 else:
1685 chars = self._decoded_chars[offset:offset + n]
1686 self._decoded_chars_used += len(chars)
1687 return chars
1688
1689 def _rewind_decoded_chars(self, n):
1690 """Rewind the _decoded_chars buffer."""
1691 if self._decoded_chars_used < n:
1692 raise AssertionError("rewind decoded_chars out of bounds")
1693 self._decoded_chars_used -= n
1694
1695 def _read_chunk(self):
1696 """
1697 Read and decode the next chunk of data from the BufferedReader.
1698 """
1699
1700 # The return value is True unless EOF was reached. The decoded
1701 # string is placed in self._decoded_chars (replacing its previous
1702 # value). The entire input chunk is sent to the decoder, though
1703 # some of it may remain buffered in the decoder, yet to be
1704 # converted.
1705
1706 if self._decoder is None:
1707 raise ValueError("no decoder")
1708
1709 if self._telling:
1710 # To prepare for tell(), we need to snapshot a point in the
1711 # file where the decoder's input buffer is empty.
1712
1713 dec_buffer, dec_flags = self._decoder.getstate()
1714 # Given this, we know there was a valid snapshot point
1715 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1716
1717 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02001718 if self._has_read1:
1719 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1720 else:
1721 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001722 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001723 decoded_chars = self._decoder.decode(input_chunk, eof)
1724 self._set_decoded_chars(decoded_chars)
1725 if decoded_chars:
1726 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
1727 else:
1728 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001729
1730 if self._telling:
1731 # At the snapshot point, len(dec_buffer) bytes before the read,
1732 # the next input to be decoded is dec_buffer + input_chunk.
1733 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1734
1735 return not eof
1736
1737 def _pack_cookie(self, position, dec_flags=0,
1738 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1739 # The meaning of a tell() cookie is: seek to position, set the
1740 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1741 # into the decoder with need_eof as the EOF flag, then skip
1742 # chars_to_skip characters of the decoded result. For most simple
1743 # decoders, tell() will often just give a byte offset in the file.
1744 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1745 (chars_to_skip<<192) | bool(need_eof)<<256)
1746
1747 def _unpack_cookie(self, bigint):
1748 rest, position = divmod(bigint, 1<<64)
1749 rest, dec_flags = divmod(rest, 1<<64)
1750 rest, bytes_to_feed = divmod(rest, 1<<64)
1751 need_eof, chars_to_skip = divmod(rest, 1<<64)
1752 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1753
1754 def tell(self):
1755 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001756 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001757 if not self._telling:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001758 raise OSError("telling position disabled by next() call")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001759 self.flush()
1760 position = self.buffer.tell()
1761 decoder = self._decoder
1762 if decoder is None or self._snapshot is None:
1763 if self._decoded_chars:
1764 # This should never happen.
1765 raise AssertionError("pending decoded text")
1766 return position
1767
1768 # Skip backward to the snapshot point (see _read_chunk).
1769 dec_flags, next_input = self._snapshot
1770 position -= len(next_input)
1771
1772 # How many decoded characters have been used up since the snapshot?
1773 chars_to_skip = self._decoded_chars_used
1774 if chars_to_skip == 0:
1775 # We haven't moved from the snapshot point.
1776 return self._pack_cookie(position, dec_flags)
1777
1778 # Starting from the snapshot position, we will walk the decoder
1779 # forward until it gives us enough decoded characters.
1780 saved_state = decoder.getstate()
1781 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001782 # Fast search for an acceptable start point, close to our
1783 # current pos.
1784 # Rationale: calling decoder.decode() has a large overhead
1785 # regardless of chunk size; we want the number of such calls to
1786 # be O(1) in most situations (common decoders, non-crazy input).
1787 # Actually, it will be exactly 1 for fixed-size codecs (all
1788 # 8-bit codecs, also UTF-16 and UTF-32).
1789 skip_bytes = int(self._b2cratio * chars_to_skip)
1790 skip_back = 1
1791 assert skip_bytes <= len(next_input)
1792 while skip_bytes > 0:
1793 decoder.setstate((b'', dec_flags))
1794 # Decode up to temptative start point
1795 n = len(decoder.decode(next_input[:skip_bytes]))
1796 if n <= chars_to_skip:
1797 b, d = decoder.getstate()
1798 if not b:
1799 # Before pos and no bytes buffered in decoder => OK
1800 dec_flags = d
1801 chars_to_skip -= n
1802 break
1803 # Skip back by buffered amount and reset heuristic
1804 skip_bytes -= len(b)
1805 skip_back = 1
1806 else:
1807 # We're too far ahead, skip back a bit
1808 skip_bytes -= skip_back
1809 skip_back = skip_back * 2
1810 else:
1811 skip_bytes = 0
1812 decoder.setstate((b'', dec_flags))
1813
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001814 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001815 start_pos = position + skip_bytes
1816 start_flags = dec_flags
1817 if chars_to_skip == 0:
1818 # We haven't moved from the start point.
1819 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001820
1821 # Feed the decoder one byte at a time. As we go, note the
1822 # nearest "safe start point" before the current location
1823 # (a point where the decoder has nothing buffered, so seek()
1824 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001825 bytes_fed = 0
1826 need_eof = 0
1827 # Chars decoded since `start_pos`
1828 chars_decoded = 0
1829 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001830 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001831 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001832 dec_buffer, dec_flags = decoder.getstate()
1833 if not dec_buffer and chars_decoded <= chars_to_skip:
1834 # Decoder buffer is empty, so this is a safe start point.
1835 start_pos += bytes_fed
1836 chars_to_skip -= chars_decoded
1837 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1838 if chars_decoded >= chars_to_skip:
1839 break
1840 else:
1841 # We didn't get enough decoded data; signal EOF to get more.
1842 chars_decoded += len(decoder.decode(b'', final=True))
1843 need_eof = 1
1844 if chars_decoded < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001845 raise OSError("can't reconstruct logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001846
1847 # The returned cookie corresponds to the last safe start point.
1848 return self._pack_cookie(
1849 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1850 finally:
1851 decoder.setstate(saved_state)
1852
1853 def truncate(self, pos=None):
1854 self.flush()
1855 if pos is None:
1856 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001857 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001858
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001859 def detach(self):
1860 if self.buffer is None:
1861 raise ValueError("buffer is already detached")
1862 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001863 buffer = self._buffer
1864 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001865 return buffer
1866
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001867 def seek(self, cookie, whence=0):
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02001868 def _reset_encoder(position):
1869 """Reset the encoder (merely useful for proper BOM handling)"""
1870 try:
1871 encoder = self._encoder or self._get_encoder()
1872 except LookupError:
1873 # Sometimes the encoder doesn't exist
1874 pass
1875 else:
1876 if position != 0:
1877 encoder.setstate(0)
1878 else:
1879 encoder.reset()
1880
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001881 if self.closed:
1882 raise ValueError("tell on closed file")
1883 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001884 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001885 if whence == 1: # seek relative to current position
1886 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001887 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001888 # Seeking to the current position should attempt to
1889 # sync the underlying buffer with the current position.
1890 whence = 0
1891 cookie = self.tell()
1892 if whence == 2: # seek relative to end of file
1893 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001894 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001895 self.flush()
1896 position = self.buffer.seek(0, 2)
1897 self._set_decoded_chars('')
1898 self._snapshot = None
1899 if self._decoder:
1900 self._decoder.reset()
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02001901 _reset_encoder(position)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001902 return position
1903 if whence != 0:
Jesus Cea94363612012-06-22 18:32:07 +02001904 raise ValueError("unsupported whence (%r)" % (whence,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001905 if cookie < 0:
1906 raise ValueError("negative seek position %r" % (cookie,))
1907 self.flush()
1908
1909 # The strategy of seek() is to go back to the safe start point
1910 # and replay the effect of read(chars_to_skip) from there.
1911 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1912 self._unpack_cookie(cookie)
1913
1914 # Seek back to the safe start point.
1915 self.buffer.seek(start_pos)
1916 self._set_decoded_chars('')
1917 self._snapshot = None
1918
1919 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001920 if cookie == 0 and self._decoder:
1921 self._decoder.reset()
1922 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001923 self._decoder = self._decoder or self._get_decoder()
1924 self._decoder.setstate((b'', dec_flags))
1925 self._snapshot = (dec_flags, b'')
1926
1927 if chars_to_skip:
1928 # Just like _read_chunk, feed the decoder and save a snapshot.
1929 input_chunk = self.buffer.read(bytes_to_feed)
1930 self._set_decoded_chars(
1931 self._decoder.decode(input_chunk, need_eof))
1932 self._snapshot = (dec_flags, input_chunk)
1933
1934 # Skip chars_to_skip of the decoded characters.
1935 if len(self._decoded_chars) < chars_to_skip:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001936 raise OSError("can't restore logical file position")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001937 self._decoded_chars_used = chars_to_skip
1938
Antoine Pitrou85e3ee72015-04-13 20:01:21 +02001939 _reset_encoder(cookie)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001940 return cookie
1941
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001942 def read(self, size=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00001943 self._checkReadable()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001944 if size is None:
1945 size = -1
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001946 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00001947 try:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001948 size.__index__
Florent Xiclunab14930c2010-03-13 15:26:44 +00001949 except AttributeError as err:
1950 raise TypeError("an integer is required") from err
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001951 if size < 0:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001952 # Read everything.
1953 result = (self._get_decoded_chars() +
1954 decoder.decode(self.buffer.read(), final=True))
1955 self._set_decoded_chars('')
1956 self._snapshot = None
1957 return result
1958 else:
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001959 # Keep reading chunks until we have size characters to return.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001960 eof = False
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001961 result = self._get_decoded_chars(size)
1962 while len(result) < size and not eof:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001963 eof = not self._read_chunk()
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001964 result += self._get_decoded_chars(size - len(result))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001965 return result
1966
1967 def __next__(self):
1968 self._telling = False
1969 line = self.readline()
1970 if not line:
1971 self._snapshot = None
1972 self._telling = self._seekable
1973 raise StopIteration
1974 return line
1975
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001976 def readline(self, size=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001977 if self.closed:
1978 raise ValueError("read from closed file")
Serhiy Storchaka3c411542013-09-16 23:18:10 +03001979 if size is None:
1980 size = -1
1981 elif not isinstance(size, int):
1982 raise TypeError("size must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001983
1984 # Grab all the decoded text (we will rewind any extra bits later).
1985 line = self._get_decoded_chars()
1986
1987 start = 0
1988 # Make the decoder if it doesn't already exist.
1989 if not self._decoder:
1990 self._get_decoder()
1991
1992 pos = endpos = None
1993 while True:
1994 if self._readtranslate:
1995 # Newlines are already translated, only search for \n
1996 pos = line.find('\n', start)
1997 if pos >= 0:
1998 endpos = pos + 1
1999 break
2000 else:
2001 start = len(line)
2002
2003 elif self._readuniversal:
2004 # Universal newline search. Find any of \r, \r\n, \n
2005 # The decoder ensures that \r\n are not split in two pieces
2006
2007 # In C we'd look for these in parallel of course.
2008 nlpos = line.find("\n", start)
2009 crpos = line.find("\r", start)
2010 if crpos == -1:
2011 if nlpos == -1:
2012 # Nothing found
2013 start = len(line)
2014 else:
2015 # Found \n
2016 endpos = nlpos + 1
2017 break
2018 elif nlpos == -1:
2019 # Found lone \r
2020 endpos = crpos + 1
2021 break
2022 elif nlpos < crpos:
2023 # Found \n
2024 endpos = nlpos + 1
2025 break
2026 elif nlpos == crpos + 1:
2027 # Found \r\n
2028 endpos = crpos + 2
2029 break
2030 else:
2031 # Found \r
2032 endpos = crpos + 1
2033 break
2034 else:
2035 # non-universal
2036 pos = line.find(self._readnl)
2037 if pos >= 0:
2038 endpos = pos + len(self._readnl)
2039 break
2040
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002041 if size >= 0 and len(line) >= size:
2042 endpos = size # reached length size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002043 break
2044
2045 # No line ending seen yet - get more data'
2046 while self._read_chunk():
2047 if self._decoded_chars:
2048 break
2049 if self._decoded_chars:
2050 line += self._get_decoded_chars()
2051 else:
2052 # end of file
2053 self._set_decoded_chars('')
2054 self._snapshot = None
2055 return line
2056
Serhiy Storchaka3c411542013-09-16 23:18:10 +03002057 if size >= 0 and endpos > size:
2058 endpos = size # don't exceed size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002059
2060 # Rewind _decoded_chars to just after the line ending we found.
2061 self._rewind_decoded_chars(len(line) - endpos)
2062 return line[:endpos]
2063
2064 @property
2065 def newlines(self):
2066 return self._decoder.newlines if self._decoder else None
2067
2068
2069class StringIO(TextIOWrapper):
2070 """Text I/O implementation using an in-memory buffer.
2071
2072 The initial_value argument sets the value of object. The newline
2073 argument is like the one of TextIOWrapper's constructor.
2074 """
2075
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002076 def __init__(self, initial_value="", newline="\n"):
2077 super(StringIO, self).__init__(BytesIO(),
2078 encoding="utf-8",
Serhiy Storchakac92ea762014-01-29 11:33:26 +02002079 errors="surrogatepass",
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002080 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002081 # Issue #5645: make universal newlines semantics the same as in the
2082 # C version, even under Windows.
2083 if newline is None:
2084 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002085 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002086 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002087 raise TypeError("initial_value must be str or None, not {0}"
2088 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002089 self.write(initial_value)
2090 self.seek(0)
2091
2092 def getvalue(self):
2093 self.flush()
Antoine Pitrou57839a62014-02-02 23:37:29 +01002094 decoder = self._decoder or self._get_decoder()
2095 old_state = decoder.getstate()
2096 decoder.reset()
2097 try:
2098 return decoder.decode(self.buffer.getvalue(), final=True)
2099 finally:
2100 decoder.setstate(old_state)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002101
2102 def __repr__(self):
2103 # TextIOWrapper tells the encoding in its repr. In StringIO,
2104 # that's a implementation detail.
2105 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002106
2107 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002108 def errors(self):
2109 return None
2110
2111 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002112 def encoding(self):
2113 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002114
2115 def detach(self):
2116 # This doesn't make sense on StringIO.
2117 self._unsupported("detach")