blob: f66290fa51aa5345efbbeca908fbe1b70ca6336c [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
Benjamin Peterson59406a92009-03-26 17:10:29 +00008import warnings
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01009import errno
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000010# Import _thread instead of threading to reduce startup cost
11try:
12 from _thread import allocate_lock as Lock
13except ImportError:
14 from _dummy_thread import allocate_lock as Lock
15
16import io
Benjamin Petersonc3be11a2010-04-27 21:24:03 +000017from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000018
19# open() uses st_blksize whenever we can
20DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
21
22# NOTE: Base classes defined here are registered with the "official" ABCs
23# defined in io.py. We don't use real inheritance though, because we don't
24# want to inherit the C implementations.
25
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020026# Rebind for compatibility
27BlockingIOError = BlockingIOError
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000028
29
Georg Brandl4d73b572011-01-13 07:13:06 +000030def open(file, mode="r", buffering=-1, encoding=None, errors=None,
Ross Lagerwall59142db2011-10-31 20:34:46 +020031 newline=None, closefd=True, opener=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000032
33 r"""Open file and return a stream. Raise IOError upon failure.
34
35 file is either a text or byte string giving the name (and the path
36 if the file isn't in the current working directory) of the file to
37 be opened or an integer file descriptor of the file to be
38 wrapped. (If a file descriptor is given, it is closed when the
39 returned I/O object is closed, unless closefd is set to False.)
40
Charles-François Natalidc3044c2012-01-09 22:40:02 +010041 mode is an optional string that specifies the mode in which the file is
42 opened. It defaults to 'r' which means open for reading in text mode. Other
43 common values are 'w' for writing (truncating the file if it already
Charles-François Natalid612de12012-01-14 11:51:00 +010044 exists), 'x' for exclusive creation of a new file, and 'a' for appending
Charles-François Natalidc3044c2012-01-09 22:40:02 +010045 (which on some Unix systems, means that all writes append to the end of the
46 file regardless of the current seek position). In text mode, if encoding is
47 not specified the encoding used is platform dependent. (For reading and
48 writing raw bytes use binary mode and leave encoding unspecified.) The
49 available modes are:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000050
51 ========= ===============================================================
52 Character Meaning
53 --------- ---------------------------------------------------------------
54 'r' open for reading (default)
55 'w' open for writing, truncating the file first
Charles-François Natalidc3044c2012-01-09 22:40:02 +010056 'x' create a new file and open it for writing
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000057 'a' open for writing, appending to the end of the file if it exists
58 'b' binary mode
59 't' text mode (default)
60 '+' open a disk file for updating (reading and writing)
61 'U' universal newline mode (for backwards compatibility; unneeded
62 for new code)
63 ========= ===============================================================
64
65 The default mode is 'rt' (open for reading text). For binary random
66 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
Charles-François Natalidc3044c2012-01-09 22:40:02 +010067 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
68 raises an `FileExistsError` if the file already exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000069
70 Python distinguishes between files opened in binary and text modes,
71 even when the underlying operating system doesn't. Files opened in
72 binary mode (appending 'b' to the mode argument) return contents as
73 bytes objects without any decoding. In text mode (the default, or when
74 't' is appended to the mode argument), the contents of the file are
75 returned as strings, the bytes having been first decoded using a
76 platform-dependent encoding or using the specified encoding if given.
77
Antoine Pitroud5587bc2009-12-19 21:08:31 +000078 buffering is an optional integer used to set the buffering policy.
79 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
80 line buffering (only usable in text mode), and an integer > 1 to indicate
81 the size of a fixed-size chunk buffer. When no buffering argument is
82 given, the default buffering policy works as follows:
83
84 * Binary files are buffered in fixed-size chunks; the size of the buffer
85 is chosen using a heuristic trying to determine the underlying device's
86 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
87 On many systems, the buffer will typically be 4096 or 8192 bytes long.
88
89 * "Interactive" text files (files for which isatty() returns True)
90 use line buffering. Other text files use the policy described above
91 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000092
Raymond Hettingercbb80892011-01-13 18:15:51 +000093 encoding is the str name of the encoding used to decode or encode the
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000094 file. This should only be used in text mode. The default encoding is
95 platform dependent, but any encoding supported by Python can be
96 passed. See the codecs module for the list of supported encodings.
97
98 errors is an optional string that specifies how encoding errors are to
99 be handled---this argument should not be used in binary mode. Pass
100 'strict' to raise a ValueError exception if there is an encoding error
101 (the default of None has the same effect), or pass 'ignore' to ignore
102 errors. (Note that ignoring encoding errors can lead to data loss.)
103 See the documentation for codecs.register for a list of the permitted
104 encoding error strings.
105
Raymond Hettingercbb80892011-01-13 18:15:51 +0000106 newline is a string controlling how universal newlines works (it only
107 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
108 as follows:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000109
110 * On input, if newline is None, universal newlines mode is
111 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
112 these are translated into '\n' before being returned to the
113 caller. If it is '', universal newline mode is enabled, but line
114 endings are returned to the caller untranslated. If it has any of
115 the other legal values, input lines are only terminated by the given
116 string, and the line ending is returned to the caller untranslated.
117
118 * On output, if newline is None, any '\n' characters written are
119 translated to the system default line separator, os.linesep. If
120 newline is '', no translation takes place. If newline is any of the
121 other legal values, any '\n' characters written are translated to
122 the given string.
123
Raymond Hettingercbb80892011-01-13 18:15:51 +0000124 closedfd is a bool. If closefd is False, the underlying file descriptor will
125 be kept open when the file is closed. This does not work when a file name is
126 given and must be True in that case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000127
Ross Lagerwall59142db2011-10-31 20:34:46 +0200128 A custom opener can be used by passing a callable as *opener*. The
129 underlying file descriptor for the file object is then obtained by calling
130 *opener* with (*file*, *flags*). *opener* must return an open file
131 descriptor (passing os.open as *opener* results in functionality similar to
132 passing None).
133
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000134 open() returns a file object whose type depends on the mode, and
135 through which the standard file operations such as reading and writing
136 are performed. When open() is used to open a file in a text mode ('w',
137 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
138 a file in a binary mode, the returned class varies: in read binary
139 mode, it returns a BufferedReader; in write binary and append binary
140 modes, it returns a BufferedWriter, and in read/write mode, it returns
141 a BufferedRandom.
142
143 It is also possible to use a string or bytearray as a file for both
144 reading and writing. For strings StringIO can be used like a file
145 opened in a text mode, and for bytes a BytesIO can be used like a file
146 opened in a binary mode.
147 """
148 if not isinstance(file, (str, bytes, int)):
149 raise TypeError("invalid file: %r" % file)
150 if not isinstance(mode, str):
151 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000152 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000153 raise TypeError("invalid buffering: %r" % buffering)
154 if encoding is not None and not isinstance(encoding, str):
155 raise TypeError("invalid encoding: %r" % encoding)
156 if errors is not None and not isinstance(errors, str):
157 raise TypeError("invalid errors: %r" % errors)
158 modes = set(mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100159 if modes - set("axrwb+tU") or len(mode) > len(modes):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000160 raise ValueError("invalid mode: %r" % mode)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100161 creating = "x" in modes
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000162 reading = "r" in modes
163 writing = "w" in modes
164 appending = "a" in modes
165 updating = "+" in modes
166 text = "t" in modes
167 binary = "b" in modes
168 if "U" in modes:
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100169 if creating or writing or appending:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000170 raise ValueError("can't use U and writing mode at once")
171 reading = True
172 if text and binary:
173 raise ValueError("can't have text and binary mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100174 if creating + reading + writing + appending > 1:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000175 raise ValueError("can't have read/write/append mode at once")
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100176 if not (creating or reading or writing or appending):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000177 raise ValueError("must have exactly one of read/write/append mode")
178 if binary and encoding is not None:
179 raise ValueError("binary mode doesn't take an encoding argument")
180 if binary and errors is not None:
181 raise ValueError("binary mode doesn't take an errors argument")
182 if binary and newline is not None:
183 raise ValueError("binary mode doesn't take a newline argument")
184 raw = FileIO(file,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100185 (creating and "x" or "") +
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000186 (reading and "r" or "") +
187 (writing and "w" or "") +
188 (appending and "a" or "") +
189 (updating and "+" or ""),
Ross Lagerwall59142db2011-10-31 20:34:46 +0200190 closefd, opener=opener)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000191 line_buffering = False
192 if buffering == 1 or buffering < 0 and raw.isatty():
193 buffering = -1
194 line_buffering = True
195 if buffering < 0:
196 buffering = DEFAULT_BUFFER_SIZE
197 try:
198 bs = os.fstat(raw.fileno()).st_blksize
199 except (os.error, AttributeError):
200 pass
201 else:
202 if bs > 1:
203 buffering = bs
204 if buffering < 0:
205 raise ValueError("invalid buffering size")
206 if buffering == 0:
207 if binary:
208 return raw
209 raise ValueError("can't have unbuffered text I/O")
210 if updating:
211 buffer = BufferedRandom(raw, buffering)
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100212 elif creating or writing or appending:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000213 buffer = BufferedWriter(raw, buffering)
214 elif reading:
215 buffer = BufferedReader(raw, buffering)
216 else:
217 raise ValueError("unknown mode: %r" % mode)
218 if binary:
219 return buffer
220 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
221 text.mode = mode
222 return text
223
224
225class DocDescriptor:
226 """Helper for builtins.open.__doc__
227 """
228 def __get__(self, obj, typ):
229 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000230 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000231 "errors=None, newline=None, closefd=True)\n\n" +
232 open.__doc__)
233
234class OpenWrapper:
235 """Wrapper for builtins.open
236
237 Trick so that open won't become a bound method when stored
238 as a class variable (as dbm.dumb does).
239
240 See initstdio() in Python/pythonrun.c.
241 """
242 __doc__ = DocDescriptor()
243
244 def __new__(cls, *args, **kwargs):
245 return open(*args, **kwargs)
246
247
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000248# In normal operation, both `UnsupportedOperation`s should be bound to the
249# same object.
250try:
251 UnsupportedOperation = io.UnsupportedOperation
252except AttributeError:
253 class UnsupportedOperation(ValueError, IOError):
254 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000255
256
257class IOBase(metaclass=abc.ABCMeta):
258
259 """The abstract base class for all I/O classes, acting on streams of
260 bytes. There is no public constructor.
261
262 This class provides dummy implementations for many methods that
263 derived classes can override selectively; the default implementations
264 represent a file that cannot be read, written or seeked.
265
266 Even though IOBase does not declare read, readinto, or write because
267 their signatures will vary, implementations and clients should
268 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000269 may raise UnsupportedOperation when operations they do not support are
270 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000271
272 The basic type used for binary data read from or written to a file is
273 bytes. bytearrays are accepted too, and in some cases (such as
274 readinto) needed. Text I/O classes work with str data.
275
276 Note that calling any method (even inquiries) on a closed stream is
277 undefined. Implementations may raise IOError in this case.
278
279 IOBase (and its subclasses) support the iterator protocol, meaning
280 that an IOBase object can be iterated over yielding the lines in a
281 stream.
282
283 IOBase also supports the :keyword:`with` statement. In this example,
284 fp is closed after the suite of the with statement is complete:
285
286 with open('spam.txt', 'r') as fp:
287 fp.write('Spam and eggs!')
288 """
289
290 ### Internal ###
291
Raymond Hettinger3c940242011-01-12 23:39:31 +0000292 def _unsupported(self, name):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000293 """Internal: raise an IOError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000294 raise UnsupportedOperation("%s.%s() not supported" %
295 (self.__class__.__name__, name))
296
297 ### Positioning ###
298
Georg Brandl4d73b572011-01-13 07:13:06 +0000299 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000300 """Change stream position.
301
302 Change the stream position to byte offset offset. offset is
303 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000304 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000305
306 * 0 -- start of stream (the default); offset should be zero or positive
307 * 1 -- current stream position; offset may be negative
308 * 2 -- end of stream; offset is usually negative
309
Raymond Hettingercbb80892011-01-13 18:15:51 +0000310 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000311 """
312 self._unsupported("seek")
313
Raymond Hettinger3c940242011-01-12 23:39:31 +0000314 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000315 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000316 return self.seek(0, 1)
317
Georg Brandl4d73b572011-01-13 07:13:06 +0000318 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000319 """Truncate file to size bytes.
320
321 Size defaults to the current IO position as reported by tell(). Return
322 the new size.
323 """
324 self._unsupported("truncate")
325
326 ### Flush and close ###
327
Raymond Hettinger3c940242011-01-12 23:39:31 +0000328 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000329 """Flush write buffers, if applicable.
330
331 This is not implemented for read-only and non-blocking streams.
332 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000333 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000334 # XXX Should this return the number of bytes written???
335
336 __closed = False
337
Raymond Hettinger3c940242011-01-12 23:39:31 +0000338 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000339 """Flush and close the IO object.
340
341 This method has no effect if the file is already closed.
342 """
343 if not self.__closed:
Antoine Pitrou6be88762010-05-03 16:48:20 +0000344 self.flush()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000345 self.__closed = True
346
Raymond Hettinger3c940242011-01-12 23:39:31 +0000347 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000348 """Destructor. Calls close()."""
349 # The try/except block is in case this is called at program
350 # exit time, when it's possible that globals have already been
351 # deleted, and then the close() call might fail. Since
352 # there's nothing we can do about such failures and they annoy
353 # the end users, we suppress the traceback.
354 try:
355 self.close()
356 except:
357 pass
358
359 ### Inquiries ###
360
Raymond Hettinger3c940242011-01-12 23:39:31 +0000361 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000362 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000363
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000364 If False, seek(), tell() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000365 This method may need to do a test seek().
366 """
367 return False
368
369 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000370 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000371 """
372 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000373 raise UnsupportedOperation("File or stream is not seekable."
374 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000375
Raymond Hettinger3c940242011-01-12 23:39:31 +0000376 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000377 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000378
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000379 If False, read() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000380 """
381 return False
382
383 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000384 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000385 """
386 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000387 raise UnsupportedOperation("File or stream is not readable."
388 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000389
Raymond Hettinger3c940242011-01-12 23:39:31 +0000390 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000391 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000392
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000393 If False, write() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000394 """
395 return False
396
397 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000398 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000399 """
400 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000401 raise UnsupportedOperation("File or stream is not writable."
402 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000403
404 @property
405 def closed(self):
406 """closed: bool. True iff the file has been closed.
407
408 For backwards compatibility, this is a property, not a predicate.
409 """
410 return self.__closed
411
412 def _checkClosed(self, msg=None):
413 """Internal: raise an ValueError if file is closed
414 """
415 if self.closed:
416 raise ValueError("I/O operation on closed file."
417 if msg is None else msg)
418
419 ### Context manager ###
420
Raymond Hettinger3c940242011-01-12 23:39:31 +0000421 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000422 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000423 self._checkClosed()
424 return self
425
Raymond Hettinger3c940242011-01-12 23:39:31 +0000426 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000427 """Context management protocol. Calls close()"""
428 self.close()
429
430 ### Lower-level APIs ###
431
432 # XXX Should these be present even if unimplemented?
433
Raymond Hettinger3c940242011-01-12 23:39:31 +0000434 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000435 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000436
437 An IOError is raised if the IO object does not use a file descriptor.
438 """
439 self._unsupported("fileno")
440
Raymond Hettinger3c940242011-01-12 23:39:31 +0000441 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000442 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000443
444 Return False if it can't be determined.
445 """
446 self._checkClosed()
447 return False
448
449 ### Readline[s] and writelines ###
450
Georg Brandl4d73b572011-01-13 07:13:06 +0000451 def readline(self, limit=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000452 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000453
454 If limit is specified, at most limit bytes will be read.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000455 Limit should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000456
457 The line terminator is always b'\n' for binary files; for text
458 files, the newlines argument to open can be used to select the line
459 terminator(s) recognized.
460 """
461 # For backwards compatibility, a (slowish) readline().
462 if hasattr(self, "peek"):
463 def nreadahead():
464 readahead = self.peek(1)
465 if not readahead:
466 return 1
467 n = (readahead.find(b"\n") + 1) or len(readahead)
468 if limit >= 0:
469 n = min(n, limit)
470 return n
471 else:
472 def nreadahead():
473 return 1
474 if limit is None:
475 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +0000476 elif not isinstance(limit, int):
477 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000478 res = bytearray()
479 while limit < 0 or len(res) < limit:
480 b = self.read(nreadahead())
481 if not b:
482 break
483 res += b
484 if res.endswith(b"\n"):
485 break
486 return bytes(res)
487
488 def __iter__(self):
489 self._checkClosed()
490 return self
491
492 def __next__(self):
493 line = self.readline()
494 if not line:
495 raise StopIteration
496 return line
497
498 def readlines(self, hint=None):
499 """Return a list of lines from the stream.
500
501 hint can be specified to control the number of lines read: no more
502 lines will be read if the total size (in bytes/characters) of all
503 lines so far exceeds hint.
504 """
505 if hint is None or hint <= 0:
506 return list(self)
507 n = 0
508 lines = []
509 for line in self:
510 lines.append(line)
511 n += len(line)
512 if n >= hint:
513 break
514 return lines
515
516 def writelines(self, lines):
517 self._checkClosed()
518 for line in lines:
519 self.write(line)
520
521io.IOBase.register(IOBase)
522
523
524class RawIOBase(IOBase):
525
526 """Base class for raw binary I/O."""
527
528 # The read() method is implemented by calling readinto(); derived
529 # classes that want to support read() only need to implement
530 # readinto() as a primitive operation. In general, readinto() can be
531 # more efficient than read().
532
533 # (It would be tempting to also provide an implementation of
534 # readinto() in terms of read(), in case the latter is a more suitable
535 # primitive operation, but that would lead to nasty recursion in case
536 # a subclass doesn't implement either.)
537
Georg Brandl4d73b572011-01-13 07:13:06 +0000538 def read(self, n=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000539 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000540
541 Returns an empty bytes object on EOF, or None if the object is
542 set not to block and has no data to read.
543 """
544 if n is None:
545 n = -1
546 if n < 0:
547 return self.readall()
548 b = bytearray(n.__index__())
549 n = self.readinto(b)
Antoine Pitrou328ec742010-09-14 18:37:24 +0000550 if n is None:
551 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000552 del b[n:]
553 return bytes(b)
554
555 def readall(self):
556 """Read until EOF, using multiple read() call."""
557 res = bytearray()
558 while True:
559 data = self.read(DEFAULT_BUFFER_SIZE)
560 if not data:
561 break
562 res += data
Victor Stinnera80987f2011-05-25 22:47:16 +0200563 if res:
564 return bytes(res)
565 else:
566 # b'' or None
567 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000568
Raymond Hettinger3c940242011-01-12 23:39:31 +0000569 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000570 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000571
Raymond Hettingercbb80892011-01-13 18:15:51 +0000572 Returns an int representing the number of bytes read (0 for EOF), or
573 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000574 """
575 self._unsupported("readinto")
576
Raymond Hettinger3c940242011-01-12 23:39:31 +0000577 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000578 """Write the given buffer to the IO stream.
579
580 Returns the number of bytes written, which may be less than len(b).
581 """
582 self._unsupported("write")
583
584io.RawIOBase.register(RawIOBase)
585from _io import FileIO
586RawIOBase.register(FileIO)
587
588
589class BufferedIOBase(IOBase):
590
591 """Base class for buffered IO objects.
592
593 The main difference with RawIOBase is that the read() method
594 supports omitting the size argument, and does not have a default
595 implementation that defers to readinto().
596
597 In addition, read(), readinto() and write() may raise
598 BlockingIOError if the underlying raw stream is in non-blocking
599 mode and not ready; unlike their raw counterparts, they will never
600 return None.
601
602 A typical implementation should not inherit from a RawIOBase
603 implementation, but wrap one.
604 """
605
Georg Brandl4d73b572011-01-13 07:13:06 +0000606 def read(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000607 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000608
609 If the argument is omitted, None, or negative, reads and
610 returns all data until EOF.
611
612 If the argument is positive, and the underlying raw stream is
613 not 'interactive', multiple raw reads may be issued to satisfy
614 the byte count (unless EOF is reached first). But for
615 interactive raw streams (XXX and for pipes?), at most one raw
616 read will be issued, and a short result does not imply that
617 EOF is imminent.
618
619 Returns an empty bytes array on EOF.
620
621 Raises BlockingIOError if the underlying raw stream has no
622 data at the moment.
623 """
624 self._unsupported("read")
625
Georg Brandl4d73b572011-01-13 07:13:06 +0000626 def read1(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000627 """Read up to n bytes with at most one read() system call,
628 where n is an int.
629 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000630 self._unsupported("read1")
631
Raymond Hettinger3c940242011-01-12 23:39:31 +0000632 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000633 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000634
635 Like read(), this may issue multiple reads to the underlying raw
636 stream, unless the latter is 'interactive'.
637
Raymond Hettingercbb80892011-01-13 18:15:51 +0000638 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000639
640 Raises BlockingIOError if the underlying raw stream has no
641 data at the moment.
642 """
643 # XXX This ought to work with anything that supports the buffer API
644 data = self.read(len(b))
645 n = len(data)
646 try:
647 b[:n] = data
648 except TypeError as err:
649 import array
650 if not isinstance(b, array.array):
651 raise err
652 b[:n] = array.array('b', data)
653 return n
654
Raymond Hettinger3c940242011-01-12 23:39:31 +0000655 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000656 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000657
658 Return the number of bytes written, which is never less than
659 len(b).
660
661 Raises BlockingIOError if the buffer is full and the
662 underlying raw stream cannot accept more data at the moment.
663 """
664 self._unsupported("write")
665
Raymond Hettinger3c940242011-01-12 23:39:31 +0000666 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000667 """
668 Separate the underlying raw stream from the buffer and return it.
669
670 After the raw stream has been detached, the buffer is in an unusable
671 state.
672 """
673 self._unsupported("detach")
674
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000675io.BufferedIOBase.register(BufferedIOBase)
676
677
678class _BufferedIOMixin(BufferedIOBase):
679
680 """A mixin implementation of BufferedIOBase with an underlying raw stream.
681
682 This passes most requests on to the underlying raw stream. It
683 does *not* provide implementations of read(), readinto() or
684 write().
685 """
686
687 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000688 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000689
690 ### Positioning ###
691
692 def seek(self, pos, whence=0):
693 new_position = self.raw.seek(pos, whence)
694 if new_position < 0:
695 raise IOError("seek() returned an invalid position")
696 return new_position
697
698 def tell(self):
699 pos = self.raw.tell()
700 if pos < 0:
701 raise IOError("tell() returned an invalid position")
702 return pos
703
704 def truncate(self, pos=None):
705 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
706 # and a flush may be necessary to synch both views of the current
707 # file state.
708 self.flush()
709
710 if pos is None:
711 pos = self.tell()
712 # XXX: Should seek() be used, instead of passing the position
713 # XXX directly to truncate?
714 return self.raw.truncate(pos)
715
716 ### Flush and close ###
717
718 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000719 if self.closed:
720 raise ValueError("flush of closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000721 self.raw.flush()
722
723 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000724 if self.raw is not None and not self.closed:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +0100725 try:
726 # may raise BlockingIOError or BrokenPipeError etc
727 self.flush()
728 finally:
729 self.raw.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000730
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000731 def detach(self):
732 if self.raw is None:
733 raise ValueError("raw stream already detached")
734 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000735 raw = self._raw
736 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000737 return raw
738
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000739 ### Inquiries ###
740
741 def seekable(self):
742 return self.raw.seekable()
743
744 def readable(self):
745 return self.raw.readable()
746
747 def writable(self):
748 return self.raw.writable()
749
750 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000751 def raw(self):
752 return self._raw
753
754 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000755 def closed(self):
756 return self.raw.closed
757
758 @property
759 def name(self):
760 return self.raw.name
761
762 @property
763 def mode(self):
764 return self.raw.mode
765
Antoine Pitrou243757e2010-11-05 21:15:39 +0000766 def __getstate__(self):
767 raise TypeError("can not serialize a '{0}' object"
768 .format(self.__class__.__name__))
769
Antoine Pitrou716c4442009-05-23 19:04:03 +0000770 def __repr__(self):
771 clsname = self.__class__.__name__
772 try:
773 name = self.name
774 except AttributeError:
775 return "<_pyio.{0}>".format(clsname)
776 else:
777 return "<_pyio.{0} name={1!r}>".format(clsname, name)
778
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000779 ### Lower-level APIs ###
780
781 def fileno(self):
782 return self.raw.fileno()
783
784 def isatty(self):
785 return self.raw.isatty()
786
787
788class BytesIO(BufferedIOBase):
789
790 """Buffered I/O implementation using an in-memory bytes buffer."""
791
792 def __init__(self, initial_bytes=None):
793 buf = bytearray()
794 if initial_bytes is not None:
795 buf += initial_bytes
796 self._buffer = buf
797 self._pos = 0
798
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000799 def __getstate__(self):
800 if self.closed:
801 raise ValueError("__getstate__ on closed file")
802 return self.__dict__.copy()
803
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000804 def getvalue(self):
805 """Return the bytes value (contents) of the buffer
806 """
807 if self.closed:
808 raise ValueError("getvalue on closed file")
809 return bytes(self._buffer)
810
Antoine Pitrou972ee132010-09-06 18:48:21 +0000811 def getbuffer(self):
812 """Return a readable and writable view of the buffer.
813 """
814 return memoryview(self._buffer)
815
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000816 def read(self, n=None):
817 if self.closed:
818 raise ValueError("read from closed file")
819 if n is None:
820 n = -1
821 if n < 0:
822 n = len(self._buffer)
823 if len(self._buffer) <= self._pos:
824 return b""
825 newpos = min(len(self._buffer), self._pos + n)
826 b = self._buffer[self._pos : newpos]
827 self._pos = newpos
828 return bytes(b)
829
830 def read1(self, n):
831 """This is the same as read.
832 """
833 return self.read(n)
834
835 def write(self, b):
836 if self.closed:
837 raise ValueError("write to closed file")
838 if isinstance(b, str):
839 raise TypeError("can't write str to binary stream")
840 n = len(b)
841 if n == 0:
842 return 0
843 pos = self._pos
844 if pos > len(self._buffer):
845 # Inserts null bytes between the current end of the file
846 # and the new write position.
847 padding = b'\x00' * (pos - len(self._buffer))
848 self._buffer += padding
849 self._buffer[pos:pos + n] = b
850 self._pos += n
851 return n
852
853 def seek(self, pos, whence=0):
854 if self.closed:
855 raise ValueError("seek on closed file")
856 try:
Florent Xiclunab14930c2010-03-13 15:26:44 +0000857 pos.__index__
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000858 except AttributeError as err:
859 raise TypeError("an integer is required") from err
860 if whence == 0:
861 if pos < 0:
862 raise ValueError("negative seek position %r" % (pos,))
863 self._pos = pos
864 elif whence == 1:
865 self._pos = max(0, self._pos + pos)
866 elif whence == 2:
867 self._pos = max(0, len(self._buffer) + pos)
868 else:
869 raise ValueError("invalid whence value")
870 return self._pos
871
872 def tell(self):
873 if self.closed:
874 raise ValueError("tell on closed file")
875 return self._pos
876
877 def truncate(self, pos=None):
878 if self.closed:
879 raise ValueError("truncate on closed file")
880 if pos is None:
881 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000882 else:
883 try:
884 pos.__index__
885 except AttributeError as err:
886 raise TypeError("an integer is required") from err
887 if pos < 0:
888 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000889 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000890 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000891
892 def readable(self):
893 return True
894
895 def writable(self):
896 return True
897
898 def seekable(self):
899 return True
900
901
902class BufferedReader(_BufferedIOMixin):
903
904 """BufferedReader(raw[, buffer_size])
905
906 A buffer for a readable, sequential BaseRawIO object.
907
908 The constructor creates a BufferedReader for the given readable raw
909 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
910 is used.
911 """
912
913 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
914 """Create a new buffered reader using the given readable raw IO object.
915 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000916 if not raw.readable():
917 raise IOError('"raw" argument must be readable.')
918
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000919 _BufferedIOMixin.__init__(self, raw)
920 if buffer_size <= 0:
921 raise ValueError("invalid buffer size")
922 self.buffer_size = buffer_size
923 self._reset_read_buf()
924 self._read_lock = Lock()
925
926 def _reset_read_buf(self):
927 self._read_buf = b""
928 self._read_pos = 0
929
930 def read(self, n=None):
931 """Read n bytes.
932
933 Returns exactly n bytes of data unless the underlying raw IO
934 stream reaches EOF or if the call would block in non-blocking
935 mode. If n is negative, read until EOF or until read() would
936 block.
937 """
938 if n is not None and n < -1:
939 raise ValueError("invalid number of bytes to read")
940 with self._read_lock:
941 return self._read_unlocked(n)
942
943 def _read_unlocked(self, n=None):
944 nodata_val = b""
945 empty_values = (b"", None)
946 buf = self._read_buf
947 pos = self._read_pos
948
949 # Special case for when the number of bytes to read is unspecified.
950 if n is None or n == -1:
951 self._reset_read_buf()
Victor Stinnerb57f1082011-05-26 00:19:38 +0200952 if hasattr(self.raw, 'readall'):
953 chunk = self.raw.readall()
954 if chunk is None:
955 return buf[pos:] or None
956 else:
957 return buf[pos:] + chunk
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000958 chunks = [buf[pos:]] # Strip the consumed bytes.
959 current_size = 0
960 while True:
961 # Read until EOF or until read() would block.
Antoine Pitrou707ce822011-02-25 21:24:11 +0000962 try:
963 chunk = self.raw.read()
Antoine Pitrou24d659d2011-10-23 23:49:42 +0200964 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +0000965 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000966 if chunk in empty_values:
967 nodata_val = chunk
968 break
969 current_size += len(chunk)
970 chunks.append(chunk)
971 return b"".join(chunks) or nodata_val
972
973 # The number of bytes to read is specified, return at most n bytes.
974 avail = len(buf) - pos # Length of the available buffered data.
975 if n <= avail:
976 # Fast path: the data to read is fully buffered.
977 self._read_pos += n
978 return buf[pos:pos+n]
979 # Slow path: read from the stream until enough bytes are read,
980 # or until an EOF occurs or until read() would block.
981 chunks = [buf[pos:]]
982 wanted = max(self.buffer_size, n)
983 while avail < n:
Antoine Pitrou707ce822011-02-25 21:24:11 +0000984 try:
985 chunk = self.raw.read(wanted)
Antoine Pitrou24d659d2011-10-23 23:49:42 +0200986 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +0000987 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000988 if chunk in empty_values:
989 nodata_val = chunk
990 break
991 avail += len(chunk)
992 chunks.append(chunk)
993 # n is more then avail only when an EOF occurred or when
994 # read() would have blocked.
995 n = min(n, avail)
996 out = b"".join(chunks)
997 self._read_buf = out[n:] # Save the extra data in the buffer.
998 self._read_pos = 0
999 return out[:n] if out else nodata_val
1000
1001 def peek(self, n=0):
1002 """Returns buffered bytes without advancing the position.
1003
1004 The argument indicates a desired minimal number of bytes; we
1005 do at most one raw read to satisfy it. We never return more
1006 than self.buffer_size.
1007 """
1008 with self._read_lock:
1009 return self._peek_unlocked(n)
1010
1011 def _peek_unlocked(self, n=0):
1012 want = min(n, self.buffer_size)
1013 have = len(self._read_buf) - self._read_pos
1014 if have < want or have <= 0:
1015 to_read = self.buffer_size - have
Antoine Pitrou707ce822011-02-25 21:24:11 +00001016 while True:
1017 try:
1018 current = self.raw.read(to_read)
Antoine Pitrou24d659d2011-10-23 23:49:42 +02001019 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001020 continue
1021 break
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001022 if current:
1023 self._read_buf = self._read_buf[self._read_pos:] + current
1024 self._read_pos = 0
1025 return self._read_buf[self._read_pos:]
1026
1027 def read1(self, n):
1028 """Reads up to n bytes, with at most one read() system call."""
1029 # Returns up to n bytes. If at least one byte is buffered, we
1030 # only return buffered bytes. Otherwise, we do one raw read.
1031 if n < 0:
1032 raise ValueError("number of bytes to read must be positive")
1033 if n == 0:
1034 return b""
1035 with self._read_lock:
1036 self._peek_unlocked(1)
1037 return self._read_unlocked(
1038 min(n, len(self._read_buf) - self._read_pos))
1039
1040 def tell(self):
1041 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1042
1043 def seek(self, pos, whence=0):
1044 if not (0 <= whence <= 2):
1045 raise ValueError("invalid whence value")
1046 with self._read_lock:
1047 if whence == 1:
1048 pos -= len(self._read_buf) - self._read_pos
1049 pos = _BufferedIOMixin.seek(self, pos, whence)
1050 self._reset_read_buf()
1051 return pos
1052
1053class BufferedWriter(_BufferedIOMixin):
1054
1055 """A buffer for a writeable sequential RawIO object.
1056
1057 The constructor creates a BufferedWriter for the given writeable raw
1058 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001059 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001060 """
1061
Benjamin Peterson59406a92009-03-26 17:10:29 +00001062 _warning_stack_offset = 2
1063
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001064 def __init__(self, raw,
1065 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001066 if not raw.writable():
1067 raise IOError('"raw" argument must be writable.')
1068
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001069 _BufferedIOMixin.__init__(self, raw)
1070 if buffer_size <= 0:
1071 raise ValueError("invalid buffer size")
Benjamin Peterson59406a92009-03-26 17:10:29 +00001072 if max_buffer_size is not None:
1073 warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
1074 self._warning_stack_offset)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001075 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001076 self._write_buf = bytearray()
1077 self._write_lock = Lock()
1078
1079 def write(self, b):
1080 if self.closed:
1081 raise ValueError("write to closed file")
1082 if isinstance(b, str):
1083 raise TypeError("can't write str to binary stream")
1084 with self._write_lock:
1085 # XXX we can implement some more tricks to try and avoid
1086 # partial writes
1087 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001088 # We're full, so let's pre-flush the buffer. (This may
1089 # raise BlockingIOError with characters_written == 0.)
1090 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001091 before = len(self._write_buf)
1092 self._write_buf.extend(b)
1093 written = len(self._write_buf) - before
1094 if len(self._write_buf) > self.buffer_size:
1095 try:
1096 self._flush_unlocked()
1097 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001098 if len(self._write_buf) > self.buffer_size:
1099 # We've hit the buffer_size. We have to accept a partial
1100 # write and cut back our buffer.
1101 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001102 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001103 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001104 raise BlockingIOError(e.errno, e.strerror, written)
1105 return written
1106
1107 def truncate(self, pos=None):
1108 with self._write_lock:
1109 self._flush_unlocked()
1110 if pos is None:
1111 pos = self.raw.tell()
1112 return self.raw.truncate(pos)
1113
1114 def flush(self):
1115 with self._write_lock:
1116 self._flush_unlocked()
1117
1118 def _flush_unlocked(self):
1119 if self.closed:
1120 raise ValueError("flush of closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001121 while self._write_buf:
1122 try:
1123 n = self.raw.write(self._write_buf)
Antoine Pitrou7fe601c2011-11-21 20:22:01 +01001124 except InterruptedError:
1125 continue
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001126 except BlockingIOError:
1127 raise RuntimeError("self.raw should implement RawIOBase: it "
1128 "should not raise BlockingIOError")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001129 if n is None:
1130 raise BlockingIOError(
1131 errno.EAGAIN,
1132 "write could not complete without blocking", 0)
1133 if n > len(self._write_buf) or n < 0:
1134 raise IOError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001135 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001136
1137 def tell(self):
1138 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1139
1140 def seek(self, pos, whence=0):
1141 if not (0 <= whence <= 2):
1142 raise ValueError("invalid whence")
1143 with self._write_lock:
1144 self._flush_unlocked()
1145 return _BufferedIOMixin.seek(self, pos, whence)
1146
1147
1148class BufferedRWPair(BufferedIOBase):
1149
1150 """A buffered reader and writer object together.
1151
1152 A buffered reader object and buffered writer object put together to
1153 form a sequential IO object that can read and write. This is typically
1154 used with a socket or two-way pipe.
1155
1156 reader and writer are RawIOBase objects that are readable and
1157 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001158 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001159 """
1160
1161 # XXX The usefulness of this (compared to having two separate IO
1162 # objects) is questionable.
1163
1164 def __init__(self, reader, writer,
1165 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1166 """Constructor.
1167
1168 The arguments are two RawIO instances.
1169 """
Benjamin Peterson59406a92009-03-26 17:10:29 +00001170 if max_buffer_size is not None:
1171 warnings.warn("max_buffer_size is deprecated", DeprecationWarning, 2)
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001172
1173 if not reader.readable():
1174 raise IOError('"reader" argument must be readable.')
1175
1176 if not writer.writable():
1177 raise IOError('"writer" argument must be writable.')
1178
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001179 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001180 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001181
1182 def read(self, n=None):
1183 if n is None:
1184 n = -1
1185 return self.reader.read(n)
1186
1187 def readinto(self, b):
1188 return self.reader.readinto(b)
1189
1190 def write(self, b):
1191 return self.writer.write(b)
1192
1193 def peek(self, n=0):
1194 return self.reader.peek(n)
1195
1196 def read1(self, n):
1197 return self.reader.read1(n)
1198
1199 def readable(self):
1200 return self.reader.readable()
1201
1202 def writable(self):
1203 return self.writer.writable()
1204
1205 def flush(self):
1206 return self.writer.flush()
1207
1208 def close(self):
1209 self.writer.close()
1210 self.reader.close()
1211
1212 def isatty(self):
1213 return self.reader.isatty() or self.writer.isatty()
1214
1215 @property
1216 def closed(self):
1217 return self.writer.closed
1218
1219
1220class BufferedRandom(BufferedWriter, BufferedReader):
1221
1222 """A buffered interface to random access streams.
1223
1224 The constructor creates a reader and writer for a seekable stream,
1225 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001226 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001227 """
1228
Benjamin Peterson59406a92009-03-26 17:10:29 +00001229 _warning_stack_offset = 3
1230
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001231 def __init__(self, raw,
1232 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1233 raw._checkSeekable()
1234 BufferedReader.__init__(self, raw, buffer_size)
1235 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1236
1237 def seek(self, pos, whence=0):
1238 if not (0 <= whence <= 2):
1239 raise ValueError("invalid whence")
1240 self.flush()
1241 if self._read_buf:
1242 # Undo read ahead.
1243 with self._read_lock:
1244 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1245 # First do the raw seek, then empty the read buffer, so that
1246 # if the raw seek fails, we don't lose buffered data forever.
1247 pos = self.raw.seek(pos, whence)
1248 with self._read_lock:
1249 self._reset_read_buf()
1250 if pos < 0:
1251 raise IOError("seek() returned invalid position")
1252 return pos
1253
1254 def tell(self):
1255 if self._write_buf:
1256 return BufferedWriter.tell(self)
1257 else:
1258 return BufferedReader.tell(self)
1259
1260 def truncate(self, pos=None):
1261 if pos is None:
1262 pos = self.tell()
1263 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001264 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001265
1266 def read(self, n=None):
1267 if n is None:
1268 n = -1
1269 self.flush()
1270 return BufferedReader.read(self, n)
1271
1272 def readinto(self, b):
1273 self.flush()
1274 return BufferedReader.readinto(self, b)
1275
1276 def peek(self, n=0):
1277 self.flush()
1278 return BufferedReader.peek(self, n)
1279
1280 def read1(self, n):
1281 self.flush()
1282 return BufferedReader.read1(self, n)
1283
1284 def write(self, b):
1285 if self._read_buf:
1286 # Undo readahead
1287 with self._read_lock:
1288 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1289 self._reset_read_buf()
1290 return BufferedWriter.write(self, b)
1291
1292
1293class TextIOBase(IOBase):
1294
1295 """Base class for text I/O.
1296
1297 This class provides a character and line based interface to stream
1298 I/O. There is no readinto method because Python's character strings
1299 are immutable. There is no public constructor.
1300 """
1301
Georg Brandl4d73b572011-01-13 07:13:06 +00001302 def read(self, n=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001303 """Read at most n characters from stream, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001304
1305 Read from underlying buffer until we have n characters or we hit EOF.
1306 If n is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001307
1308 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001309 """
1310 self._unsupported("read")
1311
Raymond Hettinger3c940242011-01-12 23:39:31 +00001312 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001313 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001314 self._unsupported("write")
1315
Georg Brandl4d73b572011-01-13 07:13:06 +00001316 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001317 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001318 self._unsupported("truncate")
1319
Raymond Hettinger3c940242011-01-12 23:39:31 +00001320 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001321 """Read until newline or EOF.
1322
1323 Returns an empty string if EOF is hit immediately.
1324 """
1325 self._unsupported("readline")
1326
Raymond Hettinger3c940242011-01-12 23:39:31 +00001327 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001328 """
1329 Separate the underlying buffer from the TextIOBase and return it.
1330
1331 After the underlying buffer has been detached, the TextIO is in an
1332 unusable state.
1333 """
1334 self._unsupported("detach")
1335
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001336 @property
1337 def encoding(self):
1338 """Subclasses should override."""
1339 return None
1340
1341 @property
1342 def newlines(self):
1343 """Line endings translated so far.
1344
1345 Only line endings translated during reading are considered.
1346
1347 Subclasses should override.
1348 """
1349 return None
1350
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001351 @property
1352 def errors(self):
1353 """Error setting of the decoder or encoder.
1354
1355 Subclasses should override."""
1356 return None
1357
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001358io.TextIOBase.register(TextIOBase)
1359
1360
1361class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1362 r"""Codec used when reading a file in universal newlines mode. It wraps
1363 another incremental decoder, translating \r\n and \r into \n. It also
1364 records the types of newlines encountered. When used with
1365 translate=False, it ensures that the newline sequence is returned in
1366 one piece.
1367 """
1368 def __init__(self, decoder, translate, errors='strict'):
1369 codecs.IncrementalDecoder.__init__(self, errors=errors)
1370 self.translate = translate
1371 self.decoder = decoder
1372 self.seennl = 0
1373 self.pendingcr = False
1374
1375 def decode(self, input, final=False):
1376 # decode input (with the eventual \r from a previous pass)
1377 if self.decoder is None:
1378 output = input
1379 else:
1380 output = self.decoder.decode(input, final=final)
1381 if self.pendingcr and (output or final):
1382 output = "\r" + output
1383 self.pendingcr = False
1384
1385 # retain last \r even when not translating data:
1386 # then readline() is sure to get \r\n in one pass
1387 if output.endswith("\r") and not final:
1388 output = output[:-1]
1389 self.pendingcr = True
1390
1391 # Record which newlines are read
1392 crlf = output.count('\r\n')
1393 cr = output.count('\r') - crlf
1394 lf = output.count('\n') - crlf
1395 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1396 | (crlf and self._CRLF)
1397
1398 if self.translate:
1399 if crlf:
1400 output = output.replace("\r\n", "\n")
1401 if cr:
1402 output = output.replace("\r", "\n")
1403
1404 return output
1405
1406 def getstate(self):
1407 if self.decoder is None:
1408 buf = b""
1409 flag = 0
1410 else:
1411 buf, flag = self.decoder.getstate()
1412 flag <<= 1
1413 if self.pendingcr:
1414 flag |= 1
1415 return buf, flag
1416
1417 def setstate(self, state):
1418 buf, flag = state
1419 self.pendingcr = bool(flag & 1)
1420 if self.decoder is not None:
1421 self.decoder.setstate((buf, flag >> 1))
1422
1423 def reset(self):
1424 self.seennl = 0
1425 self.pendingcr = False
1426 if self.decoder is not None:
1427 self.decoder.reset()
1428
1429 _LF = 1
1430 _CR = 2
1431 _CRLF = 4
1432
1433 @property
1434 def newlines(self):
1435 return (None,
1436 "\n",
1437 "\r",
1438 ("\r", "\n"),
1439 "\r\n",
1440 ("\n", "\r\n"),
1441 ("\r", "\r\n"),
1442 ("\r", "\n", "\r\n")
1443 )[self.seennl]
1444
1445
1446class TextIOWrapper(TextIOBase):
1447
1448 r"""Character and line based layer over a BufferedIOBase object, buffer.
1449
1450 encoding gives the name of the encoding that the stream will be
1451 decoded or encoded with. It defaults to locale.getpreferredencoding.
1452
1453 errors determines the strictness of encoding and decoding (see the
1454 codecs.register) and defaults to "strict".
1455
1456 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1457 handling of line endings. If it is None, universal newlines is
1458 enabled. With this enabled, on input, the lines endings '\n', '\r',
1459 or '\r\n' are translated to '\n' before being returned to the
1460 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001461 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001462 legal values, that newline becomes the newline when the file is read
1463 and it is returned untranslated. On output, '\n' is converted to the
1464 newline.
1465
1466 If line_buffering is True, a call to flush is implied when a call to
1467 write contains a newline character.
1468 """
1469
1470 _CHUNK_SIZE = 2048
1471
1472 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001473 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001474 if newline is not None and not isinstance(newline, str):
1475 raise TypeError("illegal newline type: %r" % (type(newline),))
1476 if newline not in (None, "", "\n", "\r", "\r\n"):
1477 raise ValueError("illegal newline value: %r" % (newline,))
1478 if encoding is None:
1479 try:
1480 encoding = os.device_encoding(buffer.fileno())
1481 except (AttributeError, UnsupportedOperation):
1482 pass
1483 if encoding is None:
1484 try:
1485 import locale
1486 except ImportError:
1487 # Importing locale may fail if Python is being built
1488 encoding = "ascii"
1489 else:
1490 encoding = locale.getpreferredencoding()
1491
1492 if not isinstance(encoding, str):
1493 raise ValueError("invalid encoding: %r" % encoding)
1494
1495 if errors is None:
1496 errors = "strict"
1497 else:
1498 if not isinstance(errors, str):
1499 raise ValueError("invalid errors: %r" % errors)
1500
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001501 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001502 self._line_buffering = line_buffering
1503 self._encoding = encoding
1504 self._errors = errors
1505 self._readuniversal = not newline
1506 self._readtranslate = newline is None
1507 self._readnl = newline
1508 self._writetranslate = newline != ''
1509 self._writenl = newline or os.linesep
1510 self._encoder = None
1511 self._decoder = None
1512 self._decoded_chars = '' # buffer for text returned from decoder
1513 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1514 self._snapshot = None # info for reconstructing decoder state
1515 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001516 self._has_read1 = hasattr(self.buffer, 'read1')
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001517 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001518
Antoine Pitroue4501852009-05-14 18:55:55 +00001519 if self._seekable and self.writable():
1520 position = self.buffer.tell()
1521 if position != 0:
1522 try:
1523 self._get_encoder().setstate(0)
1524 except LookupError:
1525 # Sometimes the encoder doesn't exist
1526 pass
1527
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001528 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1529 # where dec_flags is the second (integer) item of the decoder state
1530 # and next_input is the chunk of input bytes that comes next after the
1531 # snapshot point. We use this to reconstruct decoder states in tell().
1532
1533 # Naming convention:
1534 # - "bytes_..." for integer variables that count input bytes
1535 # - "chars_..." for integer variables that count decoded characters
1536
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001537 def __repr__(self):
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001538 result = "<_pyio.TextIOWrapper"
Antoine Pitrou716c4442009-05-23 19:04:03 +00001539 try:
1540 name = self.name
1541 except AttributeError:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001542 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00001543 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001544 result += " name={0!r}".format(name)
1545 try:
1546 mode = self.mode
1547 except AttributeError:
1548 pass
1549 else:
1550 result += " mode={0!r}".format(mode)
1551 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001552
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001553 @property
1554 def encoding(self):
1555 return self._encoding
1556
1557 @property
1558 def errors(self):
1559 return self._errors
1560
1561 @property
1562 def line_buffering(self):
1563 return self._line_buffering
1564
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001565 @property
1566 def buffer(self):
1567 return self._buffer
1568
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001569 def seekable(self):
1570 return self._seekable
1571
1572 def readable(self):
1573 return self.buffer.readable()
1574
1575 def writable(self):
1576 return self.buffer.writable()
1577
1578 def flush(self):
1579 self.buffer.flush()
1580 self._telling = self._seekable
1581
1582 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00001583 if self.buffer is not None and not self.closed:
1584 self.flush()
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001585 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001586
1587 @property
1588 def closed(self):
1589 return self.buffer.closed
1590
1591 @property
1592 def name(self):
1593 return self.buffer.name
1594
1595 def fileno(self):
1596 return self.buffer.fileno()
1597
1598 def isatty(self):
1599 return self.buffer.isatty()
1600
Raymond Hettinger00fa0392011-01-13 02:52:26 +00001601 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001602 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001603 if self.closed:
1604 raise ValueError("write to closed file")
1605 if not isinstance(s, str):
1606 raise TypeError("can't write %s to text stream" %
1607 s.__class__.__name__)
1608 length = len(s)
1609 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1610 if haslf and self._writetranslate and self._writenl != "\n":
1611 s = s.replace("\n", self._writenl)
1612 encoder = self._encoder or self._get_encoder()
1613 # XXX What if we were just reading?
1614 b = encoder.encode(s)
1615 self.buffer.write(b)
1616 if self._line_buffering and (haslf or "\r" in s):
1617 self.flush()
1618 self._snapshot = None
1619 if self._decoder:
1620 self._decoder.reset()
1621 return length
1622
1623 def _get_encoder(self):
1624 make_encoder = codecs.getincrementalencoder(self._encoding)
1625 self._encoder = make_encoder(self._errors)
1626 return self._encoder
1627
1628 def _get_decoder(self):
1629 make_decoder = codecs.getincrementaldecoder(self._encoding)
1630 decoder = make_decoder(self._errors)
1631 if self._readuniversal:
1632 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1633 self._decoder = decoder
1634 return decoder
1635
1636 # The following three methods implement an ADT for _decoded_chars.
1637 # Text returned from the decoder is buffered here until the client
1638 # requests it by calling our read() or readline() method.
1639 def _set_decoded_chars(self, chars):
1640 """Set the _decoded_chars buffer."""
1641 self._decoded_chars = chars
1642 self._decoded_chars_used = 0
1643
1644 def _get_decoded_chars(self, n=None):
1645 """Advance into the _decoded_chars buffer."""
1646 offset = self._decoded_chars_used
1647 if n is None:
1648 chars = self._decoded_chars[offset:]
1649 else:
1650 chars = self._decoded_chars[offset:offset + n]
1651 self._decoded_chars_used += len(chars)
1652 return chars
1653
1654 def _rewind_decoded_chars(self, n):
1655 """Rewind the _decoded_chars buffer."""
1656 if self._decoded_chars_used < n:
1657 raise AssertionError("rewind decoded_chars out of bounds")
1658 self._decoded_chars_used -= n
1659
1660 def _read_chunk(self):
1661 """
1662 Read and decode the next chunk of data from the BufferedReader.
1663 """
1664
1665 # The return value is True unless EOF was reached. The decoded
1666 # string is placed in self._decoded_chars (replacing its previous
1667 # value). The entire input chunk is sent to the decoder, though
1668 # some of it may remain buffered in the decoder, yet to be
1669 # converted.
1670
1671 if self._decoder is None:
1672 raise ValueError("no decoder")
1673
1674 if self._telling:
1675 # To prepare for tell(), we need to snapshot a point in the
1676 # file where the decoder's input buffer is empty.
1677
1678 dec_buffer, dec_flags = self._decoder.getstate()
1679 # Given this, we know there was a valid snapshot point
1680 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1681
1682 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02001683 if self._has_read1:
1684 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1685 else:
1686 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001687 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001688 decoded_chars = self._decoder.decode(input_chunk, eof)
1689 self._set_decoded_chars(decoded_chars)
1690 if decoded_chars:
1691 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
1692 else:
1693 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001694
1695 if self._telling:
1696 # At the snapshot point, len(dec_buffer) bytes before the read,
1697 # the next input to be decoded is dec_buffer + input_chunk.
1698 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1699
1700 return not eof
1701
1702 def _pack_cookie(self, position, dec_flags=0,
1703 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1704 # The meaning of a tell() cookie is: seek to position, set the
1705 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1706 # into the decoder with need_eof as the EOF flag, then skip
1707 # chars_to_skip characters of the decoded result. For most simple
1708 # decoders, tell() will often just give a byte offset in the file.
1709 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1710 (chars_to_skip<<192) | bool(need_eof)<<256)
1711
1712 def _unpack_cookie(self, bigint):
1713 rest, position = divmod(bigint, 1<<64)
1714 rest, dec_flags = divmod(rest, 1<<64)
1715 rest, bytes_to_feed = divmod(rest, 1<<64)
1716 need_eof, chars_to_skip = divmod(rest, 1<<64)
1717 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1718
1719 def tell(self):
1720 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001721 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001722 if not self._telling:
1723 raise IOError("telling position disabled by next() call")
1724 self.flush()
1725 position = self.buffer.tell()
1726 decoder = self._decoder
1727 if decoder is None or self._snapshot is None:
1728 if self._decoded_chars:
1729 # This should never happen.
1730 raise AssertionError("pending decoded text")
1731 return position
1732
1733 # Skip backward to the snapshot point (see _read_chunk).
1734 dec_flags, next_input = self._snapshot
1735 position -= len(next_input)
1736
1737 # How many decoded characters have been used up since the snapshot?
1738 chars_to_skip = self._decoded_chars_used
1739 if chars_to_skip == 0:
1740 # We haven't moved from the snapshot point.
1741 return self._pack_cookie(position, dec_flags)
1742
1743 # Starting from the snapshot position, we will walk the decoder
1744 # forward until it gives us enough decoded characters.
1745 saved_state = decoder.getstate()
1746 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001747 # Fast search for an acceptable start point, close to our
1748 # current pos.
1749 # Rationale: calling decoder.decode() has a large overhead
1750 # regardless of chunk size; we want the number of such calls to
1751 # be O(1) in most situations (common decoders, non-crazy input).
1752 # Actually, it will be exactly 1 for fixed-size codecs (all
1753 # 8-bit codecs, also UTF-16 and UTF-32).
1754 skip_bytes = int(self._b2cratio * chars_to_skip)
1755 skip_back = 1
1756 assert skip_bytes <= len(next_input)
1757 while skip_bytes > 0:
1758 decoder.setstate((b'', dec_flags))
1759 # Decode up to temptative start point
1760 n = len(decoder.decode(next_input[:skip_bytes]))
1761 if n <= chars_to_skip:
1762 b, d = decoder.getstate()
1763 if not b:
1764 # Before pos and no bytes buffered in decoder => OK
1765 dec_flags = d
1766 chars_to_skip -= n
1767 break
1768 # Skip back by buffered amount and reset heuristic
1769 skip_bytes -= len(b)
1770 skip_back = 1
1771 else:
1772 # We're too far ahead, skip back a bit
1773 skip_bytes -= skip_back
1774 skip_back = skip_back * 2
1775 else:
1776 skip_bytes = 0
1777 decoder.setstate((b'', dec_flags))
1778
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001779 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001780 start_pos = position + skip_bytes
1781 start_flags = dec_flags
1782 if chars_to_skip == 0:
1783 # We haven't moved from the start point.
1784 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001785
1786 # Feed the decoder one byte at a time. As we go, note the
1787 # nearest "safe start point" before the current location
1788 # (a point where the decoder has nothing buffered, so seek()
1789 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001790 bytes_fed = 0
1791 need_eof = 0
1792 # Chars decoded since `start_pos`
1793 chars_decoded = 0
1794 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001795 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001796 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001797 dec_buffer, dec_flags = decoder.getstate()
1798 if not dec_buffer and chars_decoded <= chars_to_skip:
1799 # Decoder buffer is empty, so this is a safe start point.
1800 start_pos += bytes_fed
1801 chars_to_skip -= chars_decoded
1802 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1803 if chars_decoded >= chars_to_skip:
1804 break
1805 else:
1806 # We didn't get enough decoded data; signal EOF to get more.
1807 chars_decoded += len(decoder.decode(b'', final=True))
1808 need_eof = 1
1809 if chars_decoded < chars_to_skip:
1810 raise IOError("can't reconstruct logical file position")
1811
1812 # The returned cookie corresponds to the last safe start point.
1813 return self._pack_cookie(
1814 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1815 finally:
1816 decoder.setstate(saved_state)
1817
1818 def truncate(self, pos=None):
1819 self.flush()
1820 if pos is None:
1821 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001822 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001823
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001824 def detach(self):
1825 if self.buffer is None:
1826 raise ValueError("buffer is already detached")
1827 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001828 buffer = self._buffer
1829 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001830 return buffer
1831
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001832 def seek(self, cookie, whence=0):
1833 if self.closed:
1834 raise ValueError("tell on closed file")
1835 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001836 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001837 if whence == 1: # seek relative to current position
1838 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001839 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001840 # Seeking to the current position should attempt to
1841 # sync the underlying buffer with the current position.
1842 whence = 0
1843 cookie = self.tell()
1844 if whence == 2: # seek relative to end of file
1845 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001846 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001847 self.flush()
1848 position = self.buffer.seek(0, 2)
1849 self._set_decoded_chars('')
1850 self._snapshot = None
1851 if self._decoder:
1852 self._decoder.reset()
1853 return position
1854 if whence != 0:
1855 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
1856 (whence,))
1857 if cookie < 0:
1858 raise ValueError("negative seek position %r" % (cookie,))
1859 self.flush()
1860
1861 # The strategy of seek() is to go back to the safe start point
1862 # and replay the effect of read(chars_to_skip) from there.
1863 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1864 self._unpack_cookie(cookie)
1865
1866 # Seek back to the safe start point.
1867 self.buffer.seek(start_pos)
1868 self._set_decoded_chars('')
1869 self._snapshot = None
1870
1871 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001872 if cookie == 0 and self._decoder:
1873 self._decoder.reset()
1874 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001875 self._decoder = self._decoder or self._get_decoder()
1876 self._decoder.setstate((b'', dec_flags))
1877 self._snapshot = (dec_flags, b'')
1878
1879 if chars_to_skip:
1880 # Just like _read_chunk, feed the decoder and save a snapshot.
1881 input_chunk = self.buffer.read(bytes_to_feed)
1882 self._set_decoded_chars(
1883 self._decoder.decode(input_chunk, need_eof))
1884 self._snapshot = (dec_flags, input_chunk)
1885
1886 # Skip chars_to_skip of the decoded characters.
1887 if len(self._decoded_chars) < chars_to_skip:
1888 raise IOError("can't restore logical file position")
1889 self._decoded_chars_used = chars_to_skip
1890
Antoine Pitroue4501852009-05-14 18:55:55 +00001891 # Finally, reset the encoder (merely useful for proper BOM handling)
1892 try:
1893 encoder = self._encoder or self._get_encoder()
1894 except LookupError:
1895 # Sometimes the encoder doesn't exist
1896 pass
1897 else:
1898 if cookie != 0:
1899 encoder.setstate(0)
1900 else:
1901 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001902 return cookie
1903
1904 def read(self, n=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00001905 self._checkReadable()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001906 if n is None:
1907 n = -1
1908 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00001909 try:
1910 n.__index__
1911 except AttributeError as err:
1912 raise TypeError("an integer is required") from err
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001913 if n < 0:
1914 # Read everything.
1915 result = (self._get_decoded_chars() +
1916 decoder.decode(self.buffer.read(), final=True))
1917 self._set_decoded_chars('')
1918 self._snapshot = None
1919 return result
1920 else:
1921 # Keep reading chunks until we have n characters to return.
1922 eof = False
1923 result = self._get_decoded_chars(n)
1924 while len(result) < n and not eof:
1925 eof = not self._read_chunk()
1926 result += self._get_decoded_chars(n - len(result))
1927 return result
1928
1929 def __next__(self):
1930 self._telling = False
1931 line = self.readline()
1932 if not line:
1933 self._snapshot = None
1934 self._telling = self._seekable
1935 raise StopIteration
1936 return line
1937
1938 def readline(self, limit=None):
1939 if self.closed:
1940 raise ValueError("read from closed file")
1941 if limit is None:
1942 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +00001943 elif not isinstance(limit, int):
1944 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001945
1946 # Grab all the decoded text (we will rewind any extra bits later).
1947 line = self._get_decoded_chars()
1948
1949 start = 0
1950 # Make the decoder if it doesn't already exist.
1951 if not self._decoder:
1952 self._get_decoder()
1953
1954 pos = endpos = None
1955 while True:
1956 if self._readtranslate:
1957 # Newlines are already translated, only search for \n
1958 pos = line.find('\n', start)
1959 if pos >= 0:
1960 endpos = pos + 1
1961 break
1962 else:
1963 start = len(line)
1964
1965 elif self._readuniversal:
1966 # Universal newline search. Find any of \r, \r\n, \n
1967 # The decoder ensures that \r\n are not split in two pieces
1968
1969 # In C we'd look for these in parallel of course.
1970 nlpos = line.find("\n", start)
1971 crpos = line.find("\r", start)
1972 if crpos == -1:
1973 if nlpos == -1:
1974 # Nothing found
1975 start = len(line)
1976 else:
1977 # Found \n
1978 endpos = nlpos + 1
1979 break
1980 elif nlpos == -1:
1981 # Found lone \r
1982 endpos = crpos + 1
1983 break
1984 elif nlpos < crpos:
1985 # Found \n
1986 endpos = nlpos + 1
1987 break
1988 elif nlpos == crpos + 1:
1989 # Found \r\n
1990 endpos = crpos + 2
1991 break
1992 else:
1993 # Found \r
1994 endpos = crpos + 1
1995 break
1996 else:
1997 # non-universal
1998 pos = line.find(self._readnl)
1999 if pos >= 0:
2000 endpos = pos + len(self._readnl)
2001 break
2002
2003 if limit >= 0 and len(line) >= limit:
2004 endpos = limit # reached length limit
2005 break
2006
2007 # No line ending seen yet - get more data'
2008 while self._read_chunk():
2009 if self._decoded_chars:
2010 break
2011 if self._decoded_chars:
2012 line += self._get_decoded_chars()
2013 else:
2014 # end of file
2015 self._set_decoded_chars('')
2016 self._snapshot = None
2017 return line
2018
2019 if limit >= 0 and endpos > limit:
2020 endpos = limit # don't exceed limit
2021
2022 # Rewind _decoded_chars to just after the line ending we found.
2023 self._rewind_decoded_chars(len(line) - endpos)
2024 return line[:endpos]
2025
2026 @property
2027 def newlines(self):
2028 return self._decoder.newlines if self._decoder else None
2029
2030
2031class StringIO(TextIOWrapper):
2032 """Text I/O implementation using an in-memory buffer.
2033
2034 The initial_value argument sets the value of object. The newline
2035 argument is like the one of TextIOWrapper's constructor.
2036 """
2037
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002038 def __init__(self, initial_value="", newline="\n"):
2039 super(StringIO, self).__init__(BytesIO(),
2040 encoding="utf-8",
2041 errors="strict",
2042 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002043 # Issue #5645: make universal newlines semantics the same as in the
2044 # C version, even under Windows.
2045 if newline is None:
2046 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002047 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002048 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002049 raise TypeError("initial_value must be str or None, not {0}"
2050 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002051 initial_value = str(initial_value)
2052 self.write(initial_value)
2053 self.seek(0)
2054
2055 def getvalue(self):
2056 self.flush()
2057 return self.buffer.getvalue().decode(self._encoding, self._errors)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002058
2059 def __repr__(self):
2060 # TextIOWrapper tells the encoding in its repr. In StringIO,
2061 # that's a implementation detail.
2062 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002063
2064 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002065 def errors(self):
2066 return None
2067
2068 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002069 def encoding(self):
2070 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002071
2072 def detach(self):
2073 # This doesn't make sense on StringIO.
2074 self._unsupported("detach")