blob: 0611bd6f820c41d837a6eed2483edbe5643fb16e [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
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
12except ImportError:
13 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)
Antoine Pitrou707ce822011-02-25 21:24:11 +000017from errno import EINTR
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,
31 newline=None, closefd=True):
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
41 mode is an optional string that specifies the mode in which the file
42 is opened. It defaults to 'r' which means open for reading in text
43 mode. Other common values are 'w' for writing (truncating the file if
44 it already exists), and 'a' for appending (which on some Unix systems,
45 means that all writes append to the end of the file regardless of the
46 current seek position). In text mode, if encoding is not specified the
47 encoding used is platform dependent. (For reading and writing raw
48 bytes use binary mode and leave encoding unspecified.) The available
49 modes are:
50
51 ========= ===============================================================
52 Character Meaning
53 --------- ---------------------------------------------------------------
54 'r' open for reading (default)
55 'w' open for writing, truncating the file first
56 'a' open for writing, appending to the end of the file if it exists
57 'b' binary mode
58 't' text mode (default)
59 '+' open a disk file for updating (reading and writing)
60 'U' universal newline mode (for backwards compatibility; unneeded
61 for new code)
62 ========= ===============================================================
63
64 The default mode is 'rt' (open for reading text). For binary random
65 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
66 'r+b' opens the file without truncation.
67
68 Python distinguishes between files opened in binary and text modes,
69 even when the underlying operating system doesn't. Files opened in
70 binary mode (appending 'b' to the mode argument) return contents as
71 bytes objects without any decoding. In text mode (the default, or when
72 't' is appended to the mode argument), the contents of the file are
73 returned as strings, the bytes having been first decoded using a
74 platform-dependent encoding or using the specified encoding if given.
75
Antoine Pitroud5587bc2009-12-19 21:08:31 +000076 buffering is an optional integer used to set the buffering policy.
77 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
78 line buffering (only usable in text mode), and an integer > 1 to indicate
79 the size of a fixed-size chunk buffer. When no buffering argument is
80 given, the default buffering policy works as follows:
81
82 * Binary files are buffered in fixed-size chunks; the size of the buffer
83 is chosen using a heuristic trying to determine the underlying device's
84 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
85 On many systems, the buffer will typically be 4096 or 8192 bytes long.
86
87 * "Interactive" text files (files for which isatty() returns True)
88 use line buffering. Other text files use the policy described above
89 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000090
Raymond Hettingercbb80892011-01-13 18:15:51 +000091 encoding is the str name of the encoding used to decode or encode the
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000092 file. This should only be used in text mode. The default encoding is
93 platform dependent, but any encoding supported by Python can be
94 passed. See the codecs module for the list of supported encodings.
95
96 errors is an optional string that specifies how encoding errors are to
97 be handled---this argument should not be used in binary mode. Pass
98 'strict' to raise a ValueError exception if there is an encoding error
99 (the default of None has the same effect), or pass 'ignore' to ignore
100 errors. (Note that ignoring encoding errors can lead to data loss.)
101 See the documentation for codecs.register for a list of the permitted
102 encoding error strings.
103
Raymond Hettingercbb80892011-01-13 18:15:51 +0000104 newline is a string controlling how universal newlines works (it only
105 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
106 as follows:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000107
108 * On input, if newline is None, universal newlines mode is
109 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
110 these are translated into '\n' before being returned to the
111 caller. If it is '', universal newline mode is enabled, but line
112 endings are returned to the caller untranslated. If it has any of
113 the other legal values, input lines are only terminated by the given
114 string, and the line ending is returned to the caller untranslated.
115
116 * On output, if newline is None, any '\n' characters written are
117 translated to the system default line separator, os.linesep. If
118 newline is '', no translation takes place. If newline is any of the
119 other legal values, any '\n' characters written are translated to
120 the given string.
121
Raymond Hettingercbb80892011-01-13 18:15:51 +0000122 closedfd is a bool. If closefd is False, the underlying file descriptor will
123 be kept open when the file is closed. This does not work when a file name is
124 given and must be True in that case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000125
126 open() returns a file object whose type depends on the mode, and
127 through which the standard file operations such as reading and writing
128 are performed. When open() is used to open a file in a text mode ('w',
129 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
130 a file in a binary mode, the returned class varies: in read binary
131 mode, it returns a BufferedReader; in write binary and append binary
132 modes, it returns a BufferedWriter, and in read/write mode, it returns
133 a BufferedRandom.
134
135 It is also possible to use a string or bytearray as a file for both
136 reading and writing. For strings StringIO can be used like a file
137 opened in a text mode, and for bytes a BytesIO can be used like a file
138 opened in a binary mode.
139 """
140 if not isinstance(file, (str, bytes, int)):
141 raise TypeError("invalid file: %r" % file)
142 if not isinstance(mode, str):
143 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000144 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000145 raise TypeError("invalid buffering: %r" % buffering)
146 if encoding is not None and not isinstance(encoding, str):
147 raise TypeError("invalid encoding: %r" % encoding)
148 if errors is not None and not isinstance(errors, str):
149 raise TypeError("invalid errors: %r" % errors)
150 modes = set(mode)
151 if modes - set("arwb+tU") or len(mode) > len(modes):
152 raise ValueError("invalid mode: %r" % mode)
153 reading = "r" in modes
154 writing = "w" in modes
155 appending = "a" in modes
156 updating = "+" in modes
157 text = "t" in modes
158 binary = "b" in modes
159 if "U" in modes:
160 if writing or appending:
161 raise ValueError("can't use U and writing mode at once")
162 reading = True
163 if text and binary:
164 raise ValueError("can't have text and binary mode at once")
165 if reading + writing + appending > 1:
166 raise ValueError("can't have read/write/append mode at once")
167 if not (reading or writing or appending):
168 raise ValueError("must have exactly one of read/write/append mode")
169 if binary and encoding is not None:
170 raise ValueError("binary mode doesn't take an encoding argument")
171 if binary and errors is not None:
172 raise ValueError("binary mode doesn't take an errors argument")
173 if binary and newline is not None:
174 raise ValueError("binary mode doesn't take a newline argument")
175 raw = FileIO(file,
176 (reading and "r" or "") +
177 (writing and "w" or "") +
178 (appending and "a" or "") +
179 (updating and "+" or ""),
180 closefd)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000181 line_buffering = False
182 if buffering == 1 or buffering < 0 and raw.isatty():
183 buffering = -1
184 line_buffering = True
185 if buffering < 0:
186 buffering = DEFAULT_BUFFER_SIZE
187 try:
188 bs = os.fstat(raw.fileno()).st_blksize
189 except (os.error, AttributeError):
190 pass
191 else:
192 if bs > 1:
193 buffering = bs
194 if buffering < 0:
195 raise ValueError("invalid buffering size")
196 if buffering == 0:
197 if binary:
198 return raw
199 raise ValueError("can't have unbuffered text I/O")
200 if updating:
201 buffer = BufferedRandom(raw, buffering)
202 elif writing or appending:
203 buffer = BufferedWriter(raw, buffering)
204 elif reading:
205 buffer = BufferedReader(raw, buffering)
206 else:
207 raise ValueError("unknown mode: %r" % mode)
208 if binary:
209 return buffer
210 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
211 text.mode = mode
212 return text
213
214
215class DocDescriptor:
216 """Helper for builtins.open.__doc__
217 """
218 def __get__(self, obj, typ):
219 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000220 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000221 "errors=None, newline=None, closefd=True)\n\n" +
222 open.__doc__)
223
224class OpenWrapper:
225 """Wrapper for builtins.open
226
227 Trick so that open won't become a bound method when stored
228 as a class variable (as dbm.dumb does).
229
230 See initstdio() in Python/pythonrun.c.
231 """
232 __doc__ = DocDescriptor()
233
234 def __new__(cls, *args, **kwargs):
235 return open(*args, **kwargs)
236
237
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000238# In normal operation, both `UnsupportedOperation`s should be bound to the
239# same object.
240try:
241 UnsupportedOperation = io.UnsupportedOperation
242except AttributeError:
243 class UnsupportedOperation(ValueError, IOError):
244 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000245
246
247class IOBase(metaclass=abc.ABCMeta):
248
249 """The abstract base class for all I/O classes, acting on streams of
250 bytes. There is no public constructor.
251
252 This class provides dummy implementations for many methods that
253 derived classes can override selectively; the default implementations
254 represent a file that cannot be read, written or seeked.
255
256 Even though IOBase does not declare read, readinto, or write because
257 their signatures will vary, implementations and clients should
258 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000259 may raise UnsupportedOperation when operations they do not support are
260 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000261
262 The basic type used for binary data read from or written to a file is
263 bytes. bytearrays are accepted too, and in some cases (such as
264 readinto) needed. Text I/O classes work with str data.
265
266 Note that calling any method (even inquiries) on a closed stream is
267 undefined. Implementations may raise IOError in this case.
268
269 IOBase (and its subclasses) support the iterator protocol, meaning
270 that an IOBase object can be iterated over yielding the lines in a
271 stream.
272
273 IOBase also supports the :keyword:`with` statement. In this example,
274 fp is closed after the suite of the with statement is complete:
275
276 with open('spam.txt', 'r') as fp:
277 fp.write('Spam and eggs!')
278 """
279
280 ### Internal ###
281
Raymond Hettinger3c940242011-01-12 23:39:31 +0000282 def _unsupported(self, name):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000283 """Internal: raise an IOError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000284 raise UnsupportedOperation("%s.%s() not supported" %
285 (self.__class__.__name__, name))
286
287 ### Positioning ###
288
Georg Brandl4d73b572011-01-13 07:13:06 +0000289 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000290 """Change stream position.
291
292 Change the stream position to byte offset offset. offset is
293 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000294 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000295
296 * 0 -- start of stream (the default); offset should be zero or positive
297 * 1 -- current stream position; offset may be negative
298 * 2 -- end of stream; offset is usually negative
299
Raymond Hettingercbb80892011-01-13 18:15:51 +0000300 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000301 """
302 self._unsupported("seek")
303
Raymond Hettinger3c940242011-01-12 23:39:31 +0000304 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000305 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000306 return self.seek(0, 1)
307
Georg Brandl4d73b572011-01-13 07:13:06 +0000308 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000309 """Truncate file to size bytes.
310
311 Size defaults to the current IO position as reported by tell(). Return
312 the new size.
313 """
314 self._unsupported("truncate")
315
316 ### Flush and close ###
317
Raymond Hettinger3c940242011-01-12 23:39:31 +0000318 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000319 """Flush write buffers, if applicable.
320
321 This is not implemented for read-only and non-blocking streams.
322 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000323 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000324 # XXX Should this return the number of bytes written???
325
326 __closed = False
327
Raymond Hettinger3c940242011-01-12 23:39:31 +0000328 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000329 """Flush and close the IO object.
330
331 This method has no effect if the file is already closed.
332 """
333 if not self.__closed:
Antoine Pitrou6be88762010-05-03 16:48:20 +0000334 self.flush()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000335 self.__closed = True
336
Raymond Hettinger3c940242011-01-12 23:39:31 +0000337 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000338 """Destructor. Calls close()."""
339 # The try/except block is in case this is called at program
340 # exit time, when it's possible that globals have already been
341 # deleted, and then the close() call might fail. Since
342 # there's nothing we can do about such failures and they annoy
343 # the end users, we suppress the traceback.
344 try:
345 self.close()
346 except:
347 pass
348
349 ### Inquiries ###
350
Raymond Hettinger3c940242011-01-12 23:39:31 +0000351 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000352 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000353
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000354 If False, seek(), tell() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000355 This method may need to do a test seek().
356 """
357 return False
358
359 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000360 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000361 """
362 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000363 raise UnsupportedOperation("File or stream is not seekable."
364 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000365
Raymond Hettinger3c940242011-01-12 23:39:31 +0000366 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000367 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000368
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000369 If False, read() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000370 """
371 return False
372
373 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000374 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000375 """
376 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000377 raise UnsupportedOperation("File or stream is not readable."
378 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000379
Raymond Hettinger3c940242011-01-12 23:39:31 +0000380 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000381 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000382
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000383 If False, write() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000384 """
385 return False
386
387 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000388 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000389 """
390 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000391 raise UnsupportedOperation("File or stream is not writable."
392 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000393
394 @property
395 def closed(self):
396 """closed: bool. True iff the file has been closed.
397
398 For backwards compatibility, this is a property, not a predicate.
399 """
400 return self.__closed
401
402 def _checkClosed(self, msg=None):
403 """Internal: raise an ValueError if file is closed
404 """
405 if self.closed:
406 raise ValueError("I/O operation on closed file."
407 if msg is None else msg)
408
409 ### Context manager ###
410
Raymond Hettinger3c940242011-01-12 23:39:31 +0000411 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000412 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000413 self._checkClosed()
414 return self
415
Raymond Hettinger3c940242011-01-12 23:39:31 +0000416 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000417 """Context management protocol. Calls close()"""
418 self.close()
419
420 ### Lower-level APIs ###
421
422 # XXX Should these be present even if unimplemented?
423
Raymond Hettinger3c940242011-01-12 23:39:31 +0000424 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000425 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000426
427 An IOError is raised if the IO object does not use a file descriptor.
428 """
429 self._unsupported("fileno")
430
Raymond Hettinger3c940242011-01-12 23:39:31 +0000431 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000432 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000433
434 Return False if it can't be determined.
435 """
436 self._checkClosed()
437 return False
438
439 ### Readline[s] and writelines ###
440
Georg Brandl4d73b572011-01-13 07:13:06 +0000441 def readline(self, limit=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000442 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000443
444 If limit is specified, at most limit bytes will be read.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000445 Limit should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000446
447 The line terminator is always b'\n' for binary files; for text
448 files, the newlines argument to open can be used to select the line
449 terminator(s) recognized.
450 """
451 # For backwards compatibility, a (slowish) readline().
452 if hasattr(self, "peek"):
453 def nreadahead():
454 readahead = self.peek(1)
455 if not readahead:
456 return 1
457 n = (readahead.find(b"\n") + 1) or len(readahead)
458 if limit >= 0:
459 n = min(n, limit)
460 return n
461 else:
462 def nreadahead():
463 return 1
464 if limit is None:
465 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +0000466 elif not isinstance(limit, int):
467 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000468 res = bytearray()
469 while limit < 0 or len(res) < limit:
470 b = self.read(nreadahead())
471 if not b:
472 break
473 res += b
474 if res.endswith(b"\n"):
475 break
476 return bytes(res)
477
478 def __iter__(self):
479 self._checkClosed()
480 return self
481
482 def __next__(self):
483 line = self.readline()
484 if not line:
485 raise StopIteration
486 return line
487
488 def readlines(self, hint=None):
489 """Return a list of lines from the stream.
490
491 hint can be specified to control the number of lines read: no more
492 lines will be read if the total size (in bytes/characters) of all
493 lines so far exceeds hint.
494 """
495 if hint is None or hint <= 0:
496 return list(self)
497 n = 0
498 lines = []
499 for line in self:
500 lines.append(line)
501 n += len(line)
502 if n >= hint:
503 break
504 return lines
505
506 def writelines(self, lines):
507 self._checkClosed()
508 for line in lines:
509 self.write(line)
510
511io.IOBase.register(IOBase)
512
513
514class RawIOBase(IOBase):
515
516 """Base class for raw binary I/O."""
517
518 # The read() method is implemented by calling readinto(); derived
519 # classes that want to support read() only need to implement
520 # readinto() as a primitive operation. In general, readinto() can be
521 # more efficient than read().
522
523 # (It would be tempting to also provide an implementation of
524 # readinto() in terms of read(), in case the latter is a more suitable
525 # primitive operation, but that would lead to nasty recursion in case
526 # a subclass doesn't implement either.)
527
Georg Brandl4d73b572011-01-13 07:13:06 +0000528 def read(self, n=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000529 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000530
531 Returns an empty bytes object on EOF, or None if the object is
532 set not to block and has no data to read.
533 """
534 if n is None:
535 n = -1
536 if n < 0:
537 return self.readall()
538 b = bytearray(n.__index__())
539 n = self.readinto(b)
Antoine Pitrou328ec742010-09-14 18:37:24 +0000540 if n is None:
541 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000542 del b[n:]
543 return bytes(b)
544
545 def readall(self):
546 """Read until EOF, using multiple read() call."""
547 res = bytearray()
548 while True:
549 data = self.read(DEFAULT_BUFFER_SIZE)
550 if not data:
551 break
552 res += data
Victor Stinnera80987f2011-05-25 22:47:16 +0200553 if res:
554 return bytes(res)
555 else:
556 # b'' or None
557 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000558
Raymond Hettinger3c940242011-01-12 23:39:31 +0000559 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000560 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000561
Raymond Hettingercbb80892011-01-13 18:15:51 +0000562 Returns an int representing the number of bytes read (0 for EOF), or
563 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000564 """
565 self._unsupported("readinto")
566
Raymond Hettinger3c940242011-01-12 23:39:31 +0000567 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000568 """Write the given buffer to the IO stream.
569
570 Returns the number of bytes written, which may be less than len(b).
571 """
572 self._unsupported("write")
573
574io.RawIOBase.register(RawIOBase)
575from _io import FileIO
576RawIOBase.register(FileIO)
577
578
579class BufferedIOBase(IOBase):
580
581 """Base class for buffered IO objects.
582
583 The main difference with RawIOBase is that the read() method
584 supports omitting the size argument, and does not have a default
585 implementation that defers to readinto().
586
587 In addition, read(), readinto() and write() may raise
588 BlockingIOError if the underlying raw stream is in non-blocking
589 mode and not ready; unlike their raw counterparts, they will never
590 return None.
591
592 A typical implementation should not inherit from a RawIOBase
593 implementation, but wrap one.
594 """
595
Georg Brandl4d73b572011-01-13 07:13:06 +0000596 def read(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000597 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000598
599 If the argument is omitted, None, or negative, reads and
600 returns all data until EOF.
601
602 If the argument is positive, and the underlying raw stream is
603 not 'interactive', multiple raw reads may be issued to satisfy
604 the byte count (unless EOF is reached first). But for
605 interactive raw streams (XXX and for pipes?), at most one raw
606 read will be issued, and a short result does not imply that
607 EOF is imminent.
608
609 Returns an empty bytes array on EOF.
610
611 Raises BlockingIOError if the underlying raw stream has no
612 data at the moment.
613 """
614 self._unsupported("read")
615
Georg Brandl4d73b572011-01-13 07:13:06 +0000616 def read1(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000617 """Read up to n bytes with at most one read() system call,
618 where n is an int.
619 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000620 self._unsupported("read1")
621
Raymond Hettinger3c940242011-01-12 23:39:31 +0000622 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000623 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000624
625 Like read(), this may issue multiple reads to the underlying raw
626 stream, unless the latter is 'interactive'.
627
Raymond Hettingercbb80892011-01-13 18:15:51 +0000628 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000629
630 Raises BlockingIOError if the underlying raw stream has no
631 data at the moment.
632 """
633 # XXX This ought to work with anything that supports the buffer API
634 data = self.read(len(b))
635 n = len(data)
636 try:
637 b[:n] = data
638 except TypeError as err:
639 import array
640 if not isinstance(b, array.array):
641 raise err
642 b[:n] = array.array('b', data)
643 return n
644
Raymond Hettinger3c940242011-01-12 23:39:31 +0000645 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000646 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000647
648 Return the number of bytes written, which is never less than
649 len(b).
650
651 Raises BlockingIOError if the buffer is full and the
652 underlying raw stream cannot accept more data at the moment.
653 """
654 self._unsupported("write")
655
Raymond Hettinger3c940242011-01-12 23:39:31 +0000656 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000657 """
658 Separate the underlying raw stream from the buffer and return it.
659
660 After the raw stream has been detached, the buffer is in an unusable
661 state.
662 """
663 self._unsupported("detach")
664
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000665io.BufferedIOBase.register(BufferedIOBase)
666
667
668class _BufferedIOMixin(BufferedIOBase):
669
670 """A mixin implementation of BufferedIOBase with an underlying raw stream.
671
672 This passes most requests on to the underlying raw stream. It
673 does *not* provide implementations of read(), readinto() or
674 write().
675 """
676
677 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000678 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000679
680 ### Positioning ###
681
682 def seek(self, pos, whence=0):
683 new_position = self.raw.seek(pos, whence)
684 if new_position < 0:
685 raise IOError("seek() returned an invalid position")
686 return new_position
687
688 def tell(self):
689 pos = self.raw.tell()
690 if pos < 0:
691 raise IOError("tell() returned an invalid position")
692 return pos
693
694 def truncate(self, pos=None):
695 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
696 # and a flush may be necessary to synch both views of the current
697 # file state.
698 self.flush()
699
700 if pos is None:
701 pos = self.tell()
702 # XXX: Should seek() be used, instead of passing the position
703 # XXX directly to truncate?
704 return self.raw.truncate(pos)
705
706 ### Flush and close ###
707
708 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000709 if self.closed:
710 raise ValueError("flush of closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000711 self.raw.flush()
712
713 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000714 if self.raw is not None and not self.closed:
715 self.flush()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000716 self.raw.close()
717
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000718 def detach(self):
719 if self.raw is None:
720 raise ValueError("raw stream already detached")
721 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000722 raw = self._raw
723 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000724 return raw
725
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000726 ### Inquiries ###
727
728 def seekable(self):
729 return self.raw.seekable()
730
731 def readable(self):
732 return self.raw.readable()
733
734 def writable(self):
735 return self.raw.writable()
736
737 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000738 def raw(self):
739 return self._raw
740
741 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000742 def closed(self):
743 return self.raw.closed
744
745 @property
746 def name(self):
747 return self.raw.name
748
749 @property
750 def mode(self):
751 return self.raw.mode
752
Antoine Pitrou243757e2010-11-05 21:15:39 +0000753 def __getstate__(self):
754 raise TypeError("can not serialize a '{0}' object"
755 .format(self.__class__.__name__))
756
Antoine Pitrou716c4442009-05-23 19:04:03 +0000757 def __repr__(self):
758 clsname = self.__class__.__name__
759 try:
760 name = self.name
761 except AttributeError:
762 return "<_pyio.{0}>".format(clsname)
763 else:
764 return "<_pyio.{0} name={1!r}>".format(clsname, name)
765
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000766 ### Lower-level APIs ###
767
768 def fileno(self):
769 return self.raw.fileno()
770
771 def isatty(self):
772 return self.raw.isatty()
773
774
775class BytesIO(BufferedIOBase):
776
777 """Buffered I/O implementation using an in-memory bytes buffer."""
778
779 def __init__(self, initial_bytes=None):
780 buf = bytearray()
781 if initial_bytes is not None:
782 buf += initial_bytes
783 self._buffer = buf
784 self._pos = 0
785
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000786 def __getstate__(self):
787 if self.closed:
788 raise ValueError("__getstate__ on closed file")
789 return self.__dict__.copy()
790
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000791 def getvalue(self):
792 """Return the bytes value (contents) of the buffer
793 """
794 if self.closed:
795 raise ValueError("getvalue on closed file")
796 return bytes(self._buffer)
797
Antoine Pitrou972ee132010-09-06 18:48:21 +0000798 def getbuffer(self):
799 """Return a readable and writable view of the buffer.
800 """
801 return memoryview(self._buffer)
802
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000803 def read(self, n=None):
804 if self.closed:
805 raise ValueError("read from closed file")
806 if n is None:
807 n = -1
808 if n < 0:
809 n = len(self._buffer)
810 if len(self._buffer) <= self._pos:
811 return b""
812 newpos = min(len(self._buffer), self._pos + n)
813 b = self._buffer[self._pos : newpos]
814 self._pos = newpos
815 return bytes(b)
816
817 def read1(self, n):
818 """This is the same as read.
819 """
820 return self.read(n)
821
822 def write(self, b):
823 if self.closed:
824 raise ValueError("write to closed file")
825 if isinstance(b, str):
826 raise TypeError("can't write str to binary stream")
827 n = len(b)
828 if n == 0:
829 return 0
830 pos = self._pos
831 if pos > len(self._buffer):
832 # Inserts null bytes between the current end of the file
833 # and the new write position.
834 padding = b'\x00' * (pos - len(self._buffer))
835 self._buffer += padding
836 self._buffer[pos:pos + n] = b
837 self._pos += n
838 return n
839
840 def seek(self, pos, whence=0):
841 if self.closed:
842 raise ValueError("seek on closed file")
843 try:
Florent Xiclunab14930c2010-03-13 15:26:44 +0000844 pos.__index__
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000845 except AttributeError as err:
846 raise TypeError("an integer is required") from err
847 if whence == 0:
848 if pos < 0:
849 raise ValueError("negative seek position %r" % (pos,))
850 self._pos = pos
851 elif whence == 1:
852 self._pos = max(0, self._pos + pos)
853 elif whence == 2:
854 self._pos = max(0, len(self._buffer) + pos)
855 else:
856 raise ValueError("invalid whence value")
857 return self._pos
858
859 def tell(self):
860 if self.closed:
861 raise ValueError("tell on closed file")
862 return self._pos
863
864 def truncate(self, pos=None):
865 if self.closed:
866 raise ValueError("truncate on closed file")
867 if pos is None:
868 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000869 else:
870 try:
871 pos.__index__
872 except AttributeError as err:
873 raise TypeError("an integer is required") from err
874 if pos < 0:
875 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000876 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000877 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000878
879 def readable(self):
880 return True
881
882 def writable(self):
883 return True
884
885 def seekable(self):
886 return True
887
888
889class BufferedReader(_BufferedIOMixin):
890
891 """BufferedReader(raw[, buffer_size])
892
893 A buffer for a readable, sequential BaseRawIO object.
894
895 The constructor creates a BufferedReader for the given readable raw
896 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
897 is used.
898 """
899
900 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
901 """Create a new buffered reader using the given readable raw IO object.
902 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000903 if not raw.readable():
904 raise IOError('"raw" argument must be readable.')
905
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000906 _BufferedIOMixin.__init__(self, raw)
907 if buffer_size <= 0:
908 raise ValueError("invalid buffer size")
909 self.buffer_size = buffer_size
910 self._reset_read_buf()
911 self._read_lock = Lock()
912
913 def _reset_read_buf(self):
914 self._read_buf = b""
915 self._read_pos = 0
916
917 def read(self, n=None):
918 """Read n bytes.
919
920 Returns exactly n bytes of data unless the underlying raw IO
921 stream reaches EOF or if the call would block in non-blocking
922 mode. If n is negative, read until EOF or until read() would
923 block.
924 """
925 if n is not None and n < -1:
926 raise ValueError("invalid number of bytes to read")
927 with self._read_lock:
928 return self._read_unlocked(n)
929
930 def _read_unlocked(self, n=None):
931 nodata_val = b""
932 empty_values = (b"", None)
933 buf = self._read_buf
934 pos = self._read_pos
935
936 # Special case for when the number of bytes to read is unspecified.
937 if n is None or n == -1:
938 self._reset_read_buf()
Victor Stinnerb57f1082011-05-26 00:19:38 +0200939 if hasattr(self.raw, 'readall'):
940 chunk = self.raw.readall()
941 if chunk is None:
942 return buf[pos:] or None
943 else:
944 return buf[pos:] + chunk
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000945 chunks = [buf[pos:]] # Strip the consumed bytes.
946 current_size = 0
947 while True:
948 # Read until EOF or until read() would block.
Antoine Pitrou707ce822011-02-25 21:24:11 +0000949 try:
950 chunk = self.raw.read()
951 except IOError as e:
952 if e.errno != EINTR:
953 raise
954 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000955 if chunk in empty_values:
956 nodata_val = chunk
957 break
958 current_size += len(chunk)
959 chunks.append(chunk)
960 return b"".join(chunks) or nodata_val
961
962 # The number of bytes to read is specified, return at most n bytes.
963 avail = len(buf) - pos # Length of the available buffered data.
964 if n <= avail:
965 # Fast path: the data to read is fully buffered.
966 self._read_pos += n
967 return buf[pos:pos+n]
968 # Slow path: read from the stream until enough bytes are read,
969 # or until an EOF occurs or until read() would block.
970 chunks = [buf[pos:]]
971 wanted = max(self.buffer_size, n)
972 while avail < n:
Antoine Pitrou707ce822011-02-25 21:24:11 +0000973 try:
974 chunk = self.raw.read(wanted)
975 except IOError as e:
976 if e.errno != EINTR:
977 raise
978 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000979 if chunk in empty_values:
980 nodata_val = chunk
981 break
982 avail += len(chunk)
983 chunks.append(chunk)
984 # n is more then avail only when an EOF occurred or when
985 # read() would have blocked.
986 n = min(n, avail)
987 out = b"".join(chunks)
988 self._read_buf = out[n:] # Save the extra data in the buffer.
989 self._read_pos = 0
990 return out[:n] if out else nodata_val
991
992 def peek(self, n=0):
993 """Returns buffered bytes without advancing the position.
994
995 The argument indicates a desired minimal number of bytes; we
996 do at most one raw read to satisfy it. We never return more
997 than self.buffer_size.
998 """
999 with self._read_lock:
1000 return self._peek_unlocked(n)
1001
1002 def _peek_unlocked(self, n=0):
1003 want = min(n, self.buffer_size)
1004 have = len(self._read_buf) - self._read_pos
1005 if have < want or have <= 0:
1006 to_read = self.buffer_size - have
Antoine Pitrou707ce822011-02-25 21:24:11 +00001007 while True:
1008 try:
1009 current = self.raw.read(to_read)
1010 except IOError as e:
1011 if e.errno != EINTR:
1012 raise
1013 continue
1014 break
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001015 if current:
1016 self._read_buf = self._read_buf[self._read_pos:] + current
1017 self._read_pos = 0
1018 return self._read_buf[self._read_pos:]
1019
1020 def read1(self, n):
1021 """Reads up to n bytes, with at most one read() system call."""
1022 # Returns up to n bytes. If at least one byte is buffered, we
1023 # only return buffered bytes. Otherwise, we do one raw read.
1024 if n < 0:
1025 raise ValueError("number of bytes to read must be positive")
1026 if n == 0:
1027 return b""
1028 with self._read_lock:
1029 self._peek_unlocked(1)
1030 return self._read_unlocked(
1031 min(n, len(self._read_buf) - self._read_pos))
1032
1033 def tell(self):
1034 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1035
1036 def seek(self, pos, whence=0):
1037 if not (0 <= whence <= 2):
1038 raise ValueError("invalid whence value")
1039 with self._read_lock:
1040 if whence == 1:
1041 pos -= len(self._read_buf) - self._read_pos
1042 pos = _BufferedIOMixin.seek(self, pos, whence)
1043 self._reset_read_buf()
1044 return pos
1045
1046class BufferedWriter(_BufferedIOMixin):
1047
1048 """A buffer for a writeable sequential RawIO object.
1049
1050 The constructor creates a BufferedWriter for the given writeable raw
1051 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001052 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001053 """
1054
Benjamin Peterson59406a92009-03-26 17:10:29 +00001055 _warning_stack_offset = 2
1056
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001057 def __init__(self, raw,
1058 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001059 if not raw.writable():
1060 raise IOError('"raw" argument must be writable.')
1061
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001062 _BufferedIOMixin.__init__(self, raw)
1063 if buffer_size <= 0:
1064 raise ValueError("invalid buffer size")
Benjamin Peterson59406a92009-03-26 17:10:29 +00001065 if max_buffer_size is not None:
1066 warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
1067 self._warning_stack_offset)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001068 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001069 self._write_buf = bytearray()
1070 self._write_lock = Lock()
1071
1072 def write(self, b):
1073 if self.closed:
1074 raise ValueError("write to closed file")
1075 if isinstance(b, str):
1076 raise TypeError("can't write str to binary stream")
1077 with self._write_lock:
1078 # XXX we can implement some more tricks to try and avoid
1079 # partial writes
1080 if len(self._write_buf) > self.buffer_size:
1081 # We're full, so let's pre-flush the buffer
1082 try:
1083 self._flush_unlocked()
1084 except BlockingIOError as e:
1085 # We can't accept anything else.
1086 # XXX Why not just let the exception pass through?
1087 raise BlockingIOError(e.errno, e.strerror, 0)
1088 before = len(self._write_buf)
1089 self._write_buf.extend(b)
1090 written = len(self._write_buf) - before
1091 if len(self._write_buf) > self.buffer_size:
1092 try:
1093 self._flush_unlocked()
1094 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001095 if len(self._write_buf) > self.buffer_size:
1096 # We've hit the buffer_size. We have to accept a partial
1097 # write and cut back our buffer.
1098 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001099 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001100 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001101 raise BlockingIOError(e.errno, e.strerror, written)
1102 return written
1103
1104 def truncate(self, pos=None):
1105 with self._write_lock:
1106 self._flush_unlocked()
1107 if pos is None:
1108 pos = self.raw.tell()
1109 return self.raw.truncate(pos)
1110
1111 def flush(self):
1112 with self._write_lock:
1113 self._flush_unlocked()
1114
1115 def _flush_unlocked(self):
1116 if self.closed:
1117 raise ValueError("flush of closed file")
1118 written = 0
1119 try:
1120 while self._write_buf:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001121 try:
1122 n = self.raw.write(self._write_buf)
1123 except IOError as e:
1124 if e.errno != EINTR:
1125 raise
1126 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001127 if n > len(self._write_buf) or n < 0:
1128 raise IOError("write() returned incorrect number of bytes")
1129 del self._write_buf[:n]
1130 written += n
1131 except BlockingIOError as e:
1132 n = e.characters_written
1133 del self._write_buf[:n]
1134 written += n
1135 raise BlockingIOError(e.errno, e.strerror, written)
1136
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
1461 default line seperator, os.linesep. If newline is any other of its
1462 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")