blob: 39c17176706237acb82cfd103d8721302c68a3ff [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)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000017
18# open() uses st_blksize whenever we can
19DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
20
21# NOTE: Base classes defined here are registered with the "official" ABCs
22# defined in io.py. We don't use real inheritance though, because we don't
23# want to inherit the C implementations.
24
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020025# Rebind for compatibility
26BlockingIOError = BlockingIOError
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000027
28
Georg Brandl4d73b572011-01-13 07:13:06 +000029def open(file, mode="r", buffering=-1, encoding=None, errors=None,
Ross Lagerwall59142db2011-10-31 20:34:46 +020030 newline=None, closefd=True, opener=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000031
32 r"""Open file and return a stream. Raise IOError upon failure.
33
34 file is either a text or byte string giving the name (and the path
35 if the file isn't in the current working directory) of the file to
36 be opened or an integer file descriptor of the file to be
37 wrapped. (If a file descriptor is given, it is closed when the
38 returned I/O object is closed, unless closefd is set to False.)
39
40 mode is an optional string that specifies the mode in which the file
41 is opened. It defaults to 'r' which means open for reading in text
42 mode. Other common values are 'w' for writing (truncating the file if
43 it already exists), and 'a' for appending (which on some Unix systems,
44 means that all writes append to the end of the file regardless of the
45 current seek position). In text mode, if encoding is not specified the
46 encoding used is platform dependent. (For reading and writing raw
47 bytes use binary mode and leave encoding unspecified.) The available
48 modes are:
49
50 ========= ===============================================================
51 Character Meaning
52 --------- ---------------------------------------------------------------
53 'r' open for reading (default)
54 'w' open for writing, truncating the file first
55 'a' open for writing, appending to the end of the file if it exists
56 'b' binary mode
57 't' text mode (default)
58 '+' open a disk file for updating (reading and writing)
59 'U' universal newline mode (for backwards compatibility; unneeded
60 for new code)
61 ========= ===============================================================
62
63 The default mode is 'rt' (open for reading text). For binary random
64 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
65 'r+b' opens the file without truncation.
66
67 Python distinguishes between files opened in binary and text modes,
68 even when the underlying operating system doesn't. Files opened in
69 binary mode (appending 'b' to the mode argument) return contents as
70 bytes objects without any decoding. In text mode (the default, or when
71 't' is appended to the mode argument), the contents of the file are
72 returned as strings, the bytes having been first decoded using a
73 platform-dependent encoding or using the specified encoding if given.
74
Antoine Pitroud5587bc2009-12-19 21:08:31 +000075 buffering is an optional integer used to set the buffering policy.
76 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
77 line buffering (only usable in text mode), and an integer > 1 to indicate
78 the size of a fixed-size chunk buffer. When no buffering argument is
79 given, the default buffering policy works as follows:
80
81 * Binary files are buffered in fixed-size chunks; the size of the buffer
82 is chosen using a heuristic trying to determine the underlying device's
83 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
84 On many systems, the buffer will typically be 4096 or 8192 bytes long.
85
86 * "Interactive" text files (files for which isatty() returns True)
87 use line buffering. Other text files use the policy described above
88 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000089
Raymond Hettingercbb80892011-01-13 18:15:51 +000090 encoding is the str name of the encoding used to decode or encode the
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000091 file. This should only be used in text mode. The default encoding is
92 platform dependent, but any encoding supported by Python can be
93 passed. See the codecs module for the list of supported encodings.
94
95 errors is an optional string that specifies how encoding errors are to
96 be handled---this argument should not be used in binary mode. Pass
97 'strict' to raise a ValueError exception if there is an encoding error
98 (the default of None has the same effect), or pass 'ignore' to ignore
99 errors. (Note that ignoring encoding errors can lead to data loss.)
100 See the documentation for codecs.register for a list of the permitted
101 encoding error strings.
102
Raymond Hettingercbb80892011-01-13 18:15:51 +0000103 newline is a string controlling how universal newlines works (it only
104 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
105 as follows:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000106
107 * On input, if newline is None, universal newlines mode is
108 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
109 these are translated into '\n' before being returned to the
110 caller. If it is '', universal newline mode is enabled, but line
111 endings are returned to the caller untranslated. If it has any of
112 the other legal values, input lines are only terminated by the given
113 string, and the line ending is returned to the caller untranslated.
114
115 * On output, if newline is None, any '\n' characters written are
116 translated to the system default line separator, os.linesep. If
117 newline is '', no translation takes place. If newline is any of the
118 other legal values, any '\n' characters written are translated to
119 the given string.
120
Raymond Hettingercbb80892011-01-13 18:15:51 +0000121 closedfd is a bool. If closefd is False, the underlying file descriptor will
122 be kept open when the file is closed. This does not work when a file name is
123 given and must be True in that case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000124
Ross Lagerwall59142db2011-10-31 20:34:46 +0200125 A custom opener can be used by passing a callable as *opener*. The
126 underlying file descriptor for the file object is then obtained by calling
127 *opener* with (*file*, *flags*). *opener* must return an open file
128 descriptor (passing os.open as *opener* results in functionality similar to
129 passing None).
130
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000131 open() returns a file object whose type depends on the mode, and
132 through which the standard file operations such as reading and writing
133 are performed. When open() is used to open a file in a text mode ('w',
134 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
135 a file in a binary mode, the returned class varies: in read binary
136 mode, it returns a BufferedReader; in write binary and append binary
137 modes, it returns a BufferedWriter, and in read/write mode, it returns
138 a BufferedRandom.
139
140 It is also possible to use a string or bytearray as a file for both
141 reading and writing. For strings StringIO can be used like a file
142 opened in a text mode, and for bytes a BytesIO can be used like a file
143 opened in a binary mode.
144 """
145 if not isinstance(file, (str, bytes, int)):
146 raise TypeError("invalid file: %r" % file)
147 if not isinstance(mode, str):
148 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000149 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000150 raise TypeError("invalid buffering: %r" % buffering)
151 if encoding is not None and not isinstance(encoding, str):
152 raise TypeError("invalid encoding: %r" % encoding)
153 if errors is not None and not isinstance(errors, str):
154 raise TypeError("invalid errors: %r" % errors)
155 modes = set(mode)
156 if modes - set("arwb+tU") or len(mode) > len(modes):
157 raise ValueError("invalid mode: %r" % mode)
158 reading = "r" in modes
159 writing = "w" in modes
160 appending = "a" in modes
161 updating = "+" in modes
162 text = "t" in modes
163 binary = "b" in modes
164 if "U" in modes:
165 if writing or appending:
166 raise ValueError("can't use U and writing mode at once")
167 reading = True
168 if text and binary:
169 raise ValueError("can't have text and binary mode at once")
170 if reading + writing + appending > 1:
171 raise ValueError("can't have read/write/append mode at once")
172 if not (reading or writing or appending):
173 raise ValueError("must have exactly one of read/write/append mode")
174 if binary and encoding is not None:
175 raise ValueError("binary mode doesn't take an encoding argument")
176 if binary and errors is not None:
177 raise ValueError("binary mode doesn't take an errors argument")
178 if binary and newline is not None:
179 raise ValueError("binary mode doesn't take a newline argument")
180 raw = FileIO(file,
181 (reading and "r" or "") +
182 (writing and "w" or "") +
183 (appending and "a" or "") +
184 (updating and "+" or ""),
Ross Lagerwall59142db2011-10-31 20:34:46 +0200185 closefd, opener=opener)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000186 line_buffering = False
187 if buffering == 1 or buffering < 0 and raw.isatty():
188 buffering = -1
189 line_buffering = True
190 if buffering < 0:
191 buffering = DEFAULT_BUFFER_SIZE
192 try:
193 bs = os.fstat(raw.fileno()).st_blksize
194 except (os.error, AttributeError):
195 pass
196 else:
197 if bs > 1:
198 buffering = bs
199 if buffering < 0:
200 raise ValueError("invalid buffering size")
201 if buffering == 0:
202 if binary:
203 return raw
204 raise ValueError("can't have unbuffered text I/O")
205 if updating:
206 buffer = BufferedRandom(raw, buffering)
207 elif writing or appending:
208 buffer = BufferedWriter(raw, buffering)
209 elif reading:
210 buffer = BufferedReader(raw, buffering)
211 else:
212 raise ValueError("unknown mode: %r" % mode)
213 if binary:
214 return buffer
215 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
216 text.mode = mode
217 return text
218
219
220class DocDescriptor:
221 """Helper for builtins.open.__doc__
222 """
223 def __get__(self, obj, typ):
224 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000225 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000226 "errors=None, newline=None, closefd=True)\n\n" +
227 open.__doc__)
228
229class OpenWrapper:
230 """Wrapper for builtins.open
231
232 Trick so that open won't become a bound method when stored
233 as a class variable (as dbm.dumb does).
234
235 See initstdio() in Python/pythonrun.c.
236 """
237 __doc__ = DocDescriptor()
238
239 def __new__(cls, *args, **kwargs):
240 return open(*args, **kwargs)
241
242
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000243# In normal operation, both `UnsupportedOperation`s should be bound to the
244# same object.
245try:
246 UnsupportedOperation = io.UnsupportedOperation
247except AttributeError:
248 class UnsupportedOperation(ValueError, IOError):
249 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000250
251
252class IOBase(metaclass=abc.ABCMeta):
253
254 """The abstract base class for all I/O classes, acting on streams of
255 bytes. There is no public constructor.
256
257 This class provides dummy implementations for many methods that
258 derived classes can override selectively; the default implementations
259 represent a file that cannot be read, written or seeked.
260
261 Even though IOBase does not declare read, readinto, or write because
262 their signatures will vary, implementations and clients should
263 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000264 may raise UnsupportedOperation when operations they do not support are
265 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000266
267 The basic type used for binary data read from or written to a file is
268 bytes. bytearrays are accepted too, and in some cases (such as
269 readinto) needed. Text I/O classes work with str data.
270
271 Note that calling any method (even inquiries) on a closed stream is
272 undefined. Implementations may raise IOError in this case.
273
274 IOBase (and its subclasses) support the iterator protocol, meaning
275 that an IOBase object can be iterated over yielding the lines in a
276 stream.
277
278 IOBase also supports the :keyword:`with` statement. In this example,
279 fp is closed after the suite of the with statement is complete:
280
281 with open('spam.txt', 'r') as fp:
282 fp.write('Spam and eggs!')
283 """
284
285 ### Internal ###
286
Raymond Hettinger3c940242011-01-12 23:39:31 +0000287 def _unsupported(self, name):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000288 """Internal: raise an IOError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000289 raise UnsupportedOperation("%s.%s() not supported" %
290 (self.__class__.__name__, name))
291
292 ### Positioning ###
293
Georg Brandl4d73b572011-01-13 07:13:06 +0000294 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000295 """Change stream position.
296
297 Change the stream position to byte offset offset. offset is
298 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000299 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000300
301 * 0 -- start of stream (the default); offset should be zero or positive
302 * 1 -- current stream position; offset may be negative
303 * 2 -- end of stream; offset is usually negative
304
Raymond Hettingercbb80892011-01-13 18:15:51 +0000305 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000306 """
307 self._unsupported("seek")
308
Raymond Hettinger3c940242011-01-12 23:39:31 +0000309 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000310 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000311 return self.seek(0, 1)
312
Georg Brandl4d73b572011-01-13 07:13:06 +0000313 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000314 """Truncate file to size bytes.
315
316 Size defaults to the current IO position as reported by tell(). Return
317 the new size.
318 """
319 self._unsupported("truncate")
320
321 ### Flush and close ###
322
Raymond Hettinger3c940242011-01-12 23:39:31 +0000323 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000324 """Flush write buffers, if applicable.
325
326 This is not implemented for read-only and non-blocking streams.
327 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000328 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000329 # XXX Should this return the number of bytes written???
330
331 __closed = False
332
Raymond Hettinger3c940242011-01-12 23:39:31 +0000333 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000334 """Flush and close the IO object.
335
336 This method has no effect if the file is already closed.
337 """
338 if not self.__closed:
Antoine Pitrou6be88762010-05-03 16:48:20 +0000339 self.flush()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000340 self.__closed = True
341
Raymond Hettinger3c940242011-01-12 23:39:31 +0000342 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000343 """Destructor. Calls close()."""
344 # The try/except block is in case this is called at program
345 # exit time, when it's possible that globals have already been
346 # deleted, and then the close() call might fail. Since
347 # there's nothing we can do about such failures and they annoy
348 # the end users, we suppress the traceback.
349 try:
350 self.close()
351 except:
352 pass
353
354 ### Inquiries ###
355
Raymond Hettinger3c940242011-01-12 23:39:31 +0000356 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000357 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000358
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000359 If False, seek(), tell() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000360 This method may need to do a test seek().
361 """
362 return False
363
364 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000365 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000366 """
367 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000368 raise UnsupportedOperation("File or stream is not seekable."
369 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000370
Raymond Hettinger3c940242011-01-12 23:39:31 +0000371 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000372 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000373
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000374 If False, read() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000375 """
376 return False
377
378 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000379 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000380 """
381 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000382 raise UnsupportedOperation("File or stream is not readable."
383 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000384
Raymond Hettinger3c940242011-01-12 23:39:31 +0000385 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000386 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000387
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000388 If False, write() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000389 """
390 return False
391
392 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000393 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000394 """
395 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000396 raise UnsupportedOperation("File or stream is not writable."
397 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000398
399 @property
400 def closed(self):
401 """closed: bool. True iff the file has been closed.
402
403 For backwards compatibility, this is a property, not a predicate.
404 """
405 return self.__closed
406
407 def _checkClosed(self, msg=None):
408 """Internal: raise an ValueError if file is closed
409 """
410 if self.closed:
411 raise ValueError("I/O operation on closed file."
412 if msg is None else msg)
413
414 ### Context manager ###
415
Raymond Hettinger3c940242011-01-12 23:39:31 +0000416 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000417 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000418 self._checkClosed()
419 return self
420
Raymond Hettinger3c940242011-01-12 23:39:31 +0000421 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000422 """Context management protocol. Calls close()"""
423 self.close()
424
425 ### Lower-level APIs ###
426
427 # XXX Should these be present even if unimplemented?
428
Raymond Hettinger3c940242011-01-12 23:39:31 +0000429 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000430 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000431
432 An IOError is raised if the IO object does not use a file descriptor.
433 """
434 self._unsupported("fileno")
435
Raymond Hettinger3c940242011-01-12 23:39:31 +0000436 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000437 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000438
439 Return False if it can't be determined.
440 """
441 self._checkClosed()
442 return False
443
444 ### Readline[s] and writelines ###
445
Georg Brandl4d73b572011-01-13 07:13:06 +0000446 def readline(self, limit=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000447 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000448
449 If limit is specified, at most limit bytes will be read.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000450 Limit should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000451
452 The line terminator is always b'\n' for binary files; for text
453 files, the newlines argument to open can be used to select the line
454 terminator(s) recognized.
455 """
456 # For backwards compatibility, a (slowish) readline().
457 if hasattr(self, "peek"):
458 def nreadahead():
459 readahead = self.peek(1)
460 if not readahead:
461 return 1
462 n = (readahead.find(b"\n") + 1) or len(readahead)
463 if limit >= 0:
464 n = min(n, limit)
465 return n
466 else:
467 def nreadahead():
468 return 1
469 if limit is None:
470 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +0000471 elif not isinstance(limit, int):
472 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000473 res = bytearray()
474 while limit < 0 or len(res) < limit:
475 b = self.read(nreadahead())
476 if not b:
477 break
478 res += b
479 if res.endswith(b"\n"):
480 break
481 return bytes(res)
482
483 def __iter__(self):
484 self._checkClosed()
485 return self
486
487 def __next__(self):
488 line = self.readline()
489 if not line:
490 raise StopIteration
491 return line
492
493 def readlines(self, hint=None):
494 """Return a list of lines from the stream.
495
496 hint can be specified to control the number of lines read: no more
497 lines will be read if the total size (in bytes/characters) of all
498 lines so far exceeds hint.
499 """
500 if hint is None or hint <= 0:
501 return list(self)
502 n = 0
503 lines = []
504 for line in self:
505 lines.append(line)
506 n += len(line)
507 if n >= hint:
508 break
509 return lines
510
511 def writelines(self, lines):
512 self._checkClosed()
513 for line in lines:
514 self.write(line)
515
516io.IOBase.register(IOBase)
517
518
519class RawIOBase(IOBase):
520
521 """Base class for raw binary I/O."""
522
523 # The read() method is implemented by calling readinto(); derived
524 # classes that want to support read() only need to implement
525 # readinto() as a primitive operation. In general, readinto() can be
526 # more efficient than read().
527
528 # (It would be tempting to also provide an implementation of
529 # readinto() in terms of read(), in case the latter is a more suitable
530 # primitive operation, but that would lead to nasty recursion in case
531 # a subclass doesn't implement either.)
532
Georg Brandl4d73b572011-01-13 07:13:06 +0000533 def read(self, n=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000534 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000535
536 Returns an empty bytes object on EOF, or None if the object is
537 set not to block and has no data to read.
538 """
539 if n is None:
540 n = -1
541 if n < 0:
542 return self.readall()
543 b = bytearray(n.__index__())
544 n = self.readinto(b)
Antoine Pitrou328ec742010-09-14 18:37:24 +0000545 if n is None:
546 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000547 del b[n:]
548 return bytes(b)
549
550 def readall(self):
551 """Read until EOF, using multiple read() call."""
552 res = bytearray()
553 while True:
554 data = self.read(DEFAULT_BUFFER_SIZE)
555 if not data:
556 break
557 res += data
Victor Stinnera80987f2011-05-25 22:47:16 +0200558 if res:
559 return bytes(res)
560 else:
561 # b'' or None
562 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000563
Raymond Hettinger3c940242011-01-12 23:39:31 +0000564 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000565 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000566
Raymond Hettingercbb80892011-01-13 18:15:51 +0000567 Returns an int representing the number of bytes read (0 for EOF), or
568 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000569 """
570 self._unsupported("readinto")
571
Raymond Hettinger3c940242011-01-12 23:39:31 +0000572 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000573 """Write the given buffer to the IO stream.
574
575 Returns the number of bytes written, which may be less than len(b).
576 """
577 self._unsupported("write")
578
579io.RawIOBase.register(RawIOBase)
580from _io import FileIO
581RawIOBase.register(FileIO)
582
583
584class BufferedIOBase(IOBase):
585
586 """Base class for buffered IO objects.
587
588 The main difference with RawIOBase is that the read() method
589 supports omitting the size argument, and does not have a default
590 implementation that defers to readinto().
591
592 In addition, read(), readinto() and write() may raise
593 BlockingIOError if the underlying raw stream is in non-blocking
594 mode and not ready; unlike their raw counterparts, they will never
595 return None.
596
597 A typical implementation should not inherit from a RawIOBase
598 implementation, but wrap one.
599 """
600
Georg Brandl4d73b572011-01-13 07:13:06 +0000601 def read(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000602 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000603
604 If the argument is omitted, None, or negative, reads and
605 returns all data until EOF.
606
607 If the argument is positive, and the underlying raw stream is
608 not 'interactive', multiple raw reads may be issued to satisfy
609 the byte count (unless EOF is reached first). But for
610 interactive raw streams (XXX and for pipes?), at most one raw
611 read will be issued, and a short result does not imply that
612 EOF is imminent.
613
614 Returns an empty bytes array on EOF.
615
616 Raises BlockingIOError if the underlying raw stream has no
617 data at the moment.
618 """
619 self._unsupported("read")
620
Georg Brandl4d73b572011-01-13 07:13:06 +0000621 def read1(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000622 """Read up to n bytes with at most one read() system call,
623 where n is an int.
624 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000625 self._unsupported("read1")
626
Raymond Hettinger3c940242011-01-12 23:39:31 +0000627 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000628 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000629
630 Like read(), this may issue multiple reads to the underlying raw
631 stream, unless the latter is 'interactive'.
632
Raymond Hettingercbb80892011-01-13 18:15:51 +0000633 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000634
635 Raises BlockingIOError if the underlying raw stream has no
636 data at the moment.
637 """
638 # XXX This ought to work with anything that supports the buffer API
639 data = self.read(len(b))
640 n = len(data)
641 try:
642 b[:n] = data
643 except TypeError as err:
644 import array
645 if not isinstance(b, array.array):
646 raise err
647 b[:n] = array.array('b', data)
648 return n
649
Raymond Hettinger3c940242011-01-12 23:39:31 +0000650 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000651 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000652
653 Return the number of bytes written, which is never less than
654 len(b).
655
656 Raises BlockingIOError if the buffer is full and the
657 underlying raw stream cannot accept more data at the moment.
658 """
659 self._unsupported("write")
660
Raymond Hettinger3c940242011-01-12 23:39:31 +0000661 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000662 """
663 Separate the underlying raw stream from the buffer and return it.
664
665 After the raw stream has been detached, the buffer is in an unusable
666 state.
667 """
668 self._unsupported("detach")
669
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000670io.BufferedIOBase.register(BufferedIOBase)
671
672
673class _BufferedIOMixin(BufferedIOBase):
674
675 """A mixin implementation of BufferedIOBase with an underlying raw stream.
676
677 This passes most requests on to the underlying raw stream. It
678 does *not* provide implementations of read(), readinto() or
679 write().
680 """
681
682 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000683 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000684
685 ### Positioning ###
686
687 def seek(self, pos, whence=0):
688 new_position = self.raw.seek(pos, whence)
689 if new_position < 0:
690 raise IOError("seek() returned an invalid position")
691 return new_position
692
693 def tell(self):
694 pos = self.raw.tell()
695 if pos < 0:
696 raise IOError("tell() returned an invalid position")
697 return pos
698
699 def truncate(self, pos=None):
700 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
701 # and a flush may be necessary to synch both views of the current
702 # file state.
703 self.flush()
704
705 if pos is None:
706 pos = self.tell()
707 # XXX: Should seek() be used, instead of passing the position
708 # XXX directly to truncate?
709 return self.raw.truncate(pos)
710
711 ### Flush and close ###
712
713 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000714 if self.closed:
715 raise ValueError("flush of closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000716 self.raw.flush()
717
718 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000719 if self.raw is not None and not self.closed:
720 self.flush()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000721 self.raw.close()
722
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000723 def detach(self):
724 if self.raw is None:
725 raise ValueError("raw stream already detached")
726 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000727 raw = self._raw
728 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000729 return raw
730
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000731 ### Inquiries ###
732
733 def seekable(self):
734 return self.raw.seekable()
735
736 def readable(self):
737 return self.raw.readable()
738
739 def writable(self):
740 return self.raw.writable()
741
742 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000743 def raw(self):
744 return self._raw
745
746 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000747 def closed(self):
748 return self.raw.closed
749
750 @property
751 def name(self):
752 return self.raw.name
753
754 @property
755 def mode(self):
756 return self.raw.mode
757
Antoine Pitrou243757e2010-11-05 21:15:39 +0000758 def __getstate__(self):
759 raise TypeError("can not serialize a '{0}' object"
760 .format(self.__class__.__name__))
761
Antoine Pitrou716c4442009-05-23 19:04:03 +0000762 def __repr__(self):
763 clsname = self.__class__.__name__
764 try:
765 name = self.name
766 except AttributeError:
767 return "<_pyio.{0}>".format(clsname)
768 else:
769 return "<_pyio.{0} name={1!r}>".format(clsname, name)
770
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000771 ### Lower-level APIs ###
772
773 def fileno(self):
774 return self.raw.fileno()
775
776 def isatty(self):
777 return self.raw.isatty()
778
779
780class BytesIO(BufferedIOBase):
781
782 """Buffered I/O implementation using an in-memory bytes buffer."""
783
784 def __init__(self, initial_bytes=None):
785 buf = bytearray()
786 if initial_bytes is not None:
787 buf += initial_bytes
788 self._buffer = buf
789 self._pos = 0
790
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000791 def __getstate__(self):
792 if self.closed:
793 raise ValueError("__getstate__ on closed file")
794 return self.__dict__.copy()
795
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000796 def getvalue(self):
797 """Return the bytes value (contents) of the buffer
798 """
799 if self.closed:
800 raise ValueError("getvalue on closed file")
801 return bytes(self._buffer)
802
Antoine Pitrou972ee132010-09-06 18:48:21 +0000803 def getbuffer(self):
804 """Return a readable and writable view of the buffer.
805 """
806 return memoryview(self._buffer)
807
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000808 def read(self, n=None):
809 if self.closed:
810 raise ValueError("read from closed file")
811 if n is None:
812 n = -1
813 if n < 0:
814 n = len(self._buffer)
815 if len(self._buffer) <= self._pos:
816 return b""
817 newpos = min(len(self._buffer), self._pos + n)
818 b = self._buffer[self._pos : newpos]
819 self._pos = newpos
820 return bytes(b)
821
822 def read1(self, n):
823 """This is the same as read.
824 """
825 return self.read(n)
826
827 def write(self, b):
828 if self.closed:
829 raise ValueError("write to closed file")
830 if isinstance(b, str):
831 raise TypeError("can't write str to binary stream")
832 n = len(b)
833 if n == 0:
834 return 0
835 pos = self._pos
836 if pos > len(self._buffer):
837 # Inserts null bytes between the current end of the file
838 # and the new write position.
839 padding = b'\x00' * (pos - len(self._buffer))
840 self._buffer += padding
841 self._buffer[pos:pos + n] = b
842 self._pos += n
843 return n
844
845 def seek(self, pos, whence=0):
846 if self.closed:
847 raise ValueError("seek on closed file")
848 try:
Florent Xiclunab14930c2010-03-13 15:26:44 +0000849 pos.__index__
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000850 except AttributeError as err:
851 raise TypeError("an integer is required") from err
852 if whence == 0:
853 if pos < 0:
854 raise ValueError("negative seek position %r" % (pos,))
855 self._pos = pos
856 elif whence == 1:
857 self._pos = max(0, self._pos + pos)
858 elif whence == 2:
859 self._pos = max(0, len(self._buffer) + pos)
860 else:
861 raise ValueError("invalid whence value")
862 return self._pos
863
864 def tell(self):
865 if self.closed:
866 raise ValueError("tell on closed file")
867 return self._pos
868
869 def truncate(self, pos=None):
870 if self.closed:
871 raise ValueError("truncate on closed file")
872 if pos is None:
873 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000874 else:
875 try:
876 pos.__index__
877 except AttributeError as err:
878 raise TypeError("an integer is required") from err
879 if pos < 0:
880 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000881 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000882 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000883
884 def readable(self):
885 return True
886
887 def writable(self):
888 return True
889
890 def seekable(self):
891 return True
892
893
894class BufferedReader(_BufferedIOMixin):
895
896 """BufferedReader(raw[, buffer_size])
897
898 A buffer for a readable, sequential BaseRawIO object.
899
900 The constructor creates a BufferedReader for the given readable raw
901 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
902 is used.
903 """
904
905 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
906 """Create a new buffered reader using the given readable raw IO object.
907 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000908 if not raw.readable():
909 raise IOError('"raw" argument must be readable.')
910
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000911 _BufferedIOMixin.__init__(self, raw)
912 if buffer_size <= 0:
913 raise ValueError("invalid buffer size")
914 self.buffer_size = buffer_size
915 self._reset_read_buf()
916 self._read_lock = Lock()
917
918 def _reset_read_buf(self):
919 self._read_buf = b""
920 self._read_pos = 0
921
922 def read(self, n=None):
923 """Read n bytes.
924
925 Returns exactly n bytes of data unless the underlying raw IO
926 stream reaches EOF or if the call would block in non-blocking
927 mode. If n is negative, read until EOF or until read() would
928 block.
929 """
930 if n is not None and n < -1:
931 raise ValueError("invalid number of bytes to read")
932 with self._read_lock:
933 return self._read_unlocked(n)
934
935 def _read_unlocked(self, n=None):
936 nodata_val = b""
937 empty_values = (b"", None)
938 buf = self._read_buf
939 pos = self._read_pos
940
941 # Special case for when the number of bytes to read is unspecified.
942 if n is None or n == -1:
943 self._reset_read_buf()
Victor Stinnerb57f1082011-05-26 00:19:38 +0200944 if hasattr(self.raw, 'readall'):
945 chunk = self.raw.readall()
946 if chunk is None:
947 return buf[pos:] or None
948 else:
949 return buf[pos:] + chunk
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000950 chunks = [buf[pos:]] # Strip the consumed bytes.
951 current_size = 0
952 while True:
953 # Read until EOF or until read() would block.
Antoine Pitrou707ce822011-02-25 21:24:11 +0000954 try:
955 chunk = self.raw.read()
Antoine Pitrou24d659d2011-10-23 23:49:42 +0200956 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +0000957 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000958 if chunk in empty_values:
959 nodata_val = chunk
960 break
961 current_size += len(chunk)
962 chunks.append(chunk)
963 return b"".join(chunks) or nodata_val
964
965 # The number of bytes to read is specified, return at most n bytes.
966 avail = len(buf) - pos # Length of the available buffered data.
967 if n <= avail:
968 # Fast path: the data to read is fully buffered.
969 self._read_pos += n
970 return buf[pos:pos+n]
971 # Slow path: read from the stream until enough bytes are read,
972 # or until an EOF occurs or until read() would block.
973 chunks = [buf[pos:]]
974 wanted = max(self.buffer_size, n)
975 while avail < n:
Antoine Pitrou707ce822011-02-25 21:24:11 +0000976 try:
977 chunk = self.raw.read(wanted)
Antoine Pitrou24d659d2011-10-23 23:49:42 +0200978 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +0000979 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000980 if chunk in empty_values:
981 nodata_val = chunk
982 break
983 avail += len(chunk)
984 chunks.append(chunk)
985 # n is more then avail only when an EOF occurred or when
986 # read() would have blocked.
987 n = min(n, avail)
988 out = b"".join(chunks)
989 self._read_buf = out[n:] # Save the extra data in the buffer.
990 self._read_pos = 0
991 return out[:n] if out else nodata_val
992
993 def peek(self, n=0):
994 """Returns buffered bytes without advancing the position.
995
996 The argument indicates a desired minimal number of bytes; we
997 do at most one raw read to satisfy it. We never return more
998 than self.buffer_size.
999 """
1000 with self._read_lock:
1001 return self._peek_unlocked(n)
1002
1003 def _peek_unlocked(self, n=0):
1004 want = min(n, self.buffer_size)
1005 have = len(self._read_buf) - self._read_pos
1006 if have < want or have <= 0:
1007 to_read = self.buffer_size - have
Antoine Pitrou707ce822011-02-25 21:24:11 +00001008 while True:
1009 try:
1010 current = self.raw.read(to_read)
Antoine Pitrou24d659d2011-10-23 23:49:42 +02001011 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001012 continue
1013 break
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001014 if current:
1015 self._read_buf = self._read_buf[self._read_pos:] + current
1016 self._read_pos = 0
1017 return self._read_buf[self._read_pos:]
1018
1019 def read1(self, n):
1020 """Reads up to n bytes, with at most one read() system call."""
1021 # Returns up to n bytes. If at least one byte is buffered, we
1022 # only return buffered bytes. Otherwise, we do one raw read.
1023 if n < 0:
1024 raise ValueError("number of bytes to read must be positive")
1025 if n == 0:
1026 return b""
1027 with self._read_lock:
1028 self._peek_unlocked(1)
1029 return self._read_unlocked(
1030 min(n, len(self._read_buf) - self._read_pos))
1031
1032 def tell(self):
1033 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1034
1035 def seek(self, pos, whence=0):
1036 if not (0 <= whence <= 2):
1037 raise ValueError("invalid whence value")
1038 with self._read_lock:
1039 if whence == 1:
1040 pos -= len(self._read_buf) - self._read_pos
1041 pos = _BufferedIOMixin.seek(self, pos, whence)
1042 self._reset_read_buf()
1043 return pos
1044
1045class BufferedWriter(_BufferedIOMixin):
1046
1047 """A buffer for a writeable sequential RawIO object.
1048
1049 The constructor creates a BufferedWriter for the given writeable raw
1050 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001051 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001052 """
1053
Benjamin Peterson59406a92009-03-26 17:10:29 +00001054 _warning_stack_offset = 2
1055
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001056 def __init__(self, raw,
1057 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001058 if not raw.writable():
1059 raise IOError('"raw" argument must be writable.')
1060
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001061 _BufferedIOMixin.__init__(self, raw)
1062 if buffer_size <= 0:
1063 raise ValueError("invalid buffer size")
Benjamin Peterson59406a92009-03-26 17:10:29 +00001064 if max_buffer_size is not None:
1065 warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
1066 self._warning_stack_offset)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001067 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001068 self._write_buf = bytearray()
1069 self._write_lock = Lock()
1070
1071 def write(self, b):
1072 if self.closed:
1073 raise ValueError("write to closed file")
1074 if isinstance(b, str):
1075 raise TypeError("can't write str to binary stream")
1076 with self._write_lock:
1077 # XXX we can implement some more tricks to try and avoid
1078 # partial writes
1079 if len(self._write_buf) > self.buffer_size:
1080 # We're full, so let's pre-flush the buffer
1081 try:
1082 self._flush_unlocked()
1083 except BlockingIOError as e:
1084 # We can't accept anything else.
1085 # XXX Why not just let the exception pass through?
1086 raise BlockingIOError(e.errno, e.strerror, 0)
1087 before = len(self._write_buf)
1088 self._write_buf.extend(b)
1089 written = len(self._write_buf) - before
1090 if len(self._write_buf) > self.buffer_size:
1091 try:
1092 self._flush_unlocked()
1093 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001094 if len(self._write_buf) > self.buffer_size:
1095 # We've hit the buffer_size. We have to accept a partial
1096 # write and cut back our buffer.
1097 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001098 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001099 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001100 raise BlockingIOError(e.errno, e.strerror, written)
1101 return written
1102
1103 def truncate(self, pos=None):
1104 with self._write_lock:
1105 self._flush_unlocked()
1106 if pos is None:
1107 pos = self.raw.tell()
1108 return self.raw.truncate(pos)
1109
1110 def flush(self):
1111 with self._write_lock:
1112 self._flush_unlocked()
1113
1114 def _flush_unlocked(self):
1115 if self.closed:
1116 raise ValueError("flush of closed file")
1117 written = 0
1118 try:
1119 while self._write_buf:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001120 try:
1121 n = self.raw.write(self._write_buf)
Antoine Pitrou24d659d2011-10-23 23:49:42 +02001122 except InterruptedError:
Antoine Pitrou707ce822011-02-25 21:24:11 +00001123 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001124 if n > len(self._write_buf) or n < 0:
1125 raise IOError("write() returned incorrect number of bytes")
1126 del self._write_buf[:n]
1127 written += n
1128 except BlockingIOError as e:
1129 n = e.characters_written
1130 del self._write_buf[:n]
1131 written += n
1132 raise BlockingIOError(e.errno, e.strerror, written)
1133
1134 def tell(self):
1135 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1136
1137 def seek(self, pos, whence=0):
1138 if not (0 <= whence <= 2):
1139 raise ValueError("invalid whence")
1140 with self._write_lock:
1141 self._flush_unlocked()
1142 return _BufferedIOMixin.seek(self, pos, whence)
1143
1144
1145class BufferedRWPair(BufferedIOBase):
1146
1147 """A buffered reader and writer object together.
1148
1149 A buffered reader object and buffered writer object put together to
1150 form a sequential IO object that can read and write. This is typically
1151 used with a socket or two-way pipe.
1152
1153 reader and writer are RawIOBase objects that are readable and
1154 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001155 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001156 """
1157
1158 # XXX The usefulness of this (compared to having two separate IO
1159 # objects) is questionable.
1160
1161 def __init__(self, reader, writer,
1162 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1163 """Constructor.
1164
1165 The arguments are two RawIO instances.
1166 """
Benjamin Peterson59406a92009-03-26 17:10:29 +00001167 if max_buffer_size is not None:
1168 warnings.warn("max_buffer_size is deprecated", DeprecationWarning, 2)
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001169
1170 if not reader.readable():
1171 raise IOError('"reader" argument must be readable.')
1172
1173 if not writer.writable():
1174 raise IOError('"writer" argument must be writable.')
1175
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001176 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001177 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001178
1179 def read(self, n=None):
1180 if n is None:
1181 n = -1
1182 return self.reader.read(n)
1183
1184 def readinto(self, b):
1185 return self.reader.readinto(b)
1186
1187 def write(self, b):
1188 return self.writer.write(b)
1189
1190 def peek(self, n=0):
1191 return self.reader.peek(n)
1192
1193 def read1(self, n):
1194 return self.reader.read1(n)
1195
1196 def readable(self):
1197 return self.reader.readable()
1198
1199 def writable(self):
1200 return self.writer.writable()
1201
1202 def flush(self):
1203 return self.writer.flush()
1204
1205 def close(self):
1206 self.writer.close()
1207 self.reader.close()
1208
1209 def isatty(self):
1210 return self.reader.isatty() or self.writer.isatty()
1211
1212 @property
1213 def closed(self):
1214 return self.writer.closed
1215
1216
1217class BufferedRandom(BufferedWriter, BufferedReader):
1218
1219 """A buffered interface to random access streams.
1220
1221 The constructor creates a reader and writer for a seekable stream,
1222 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001223 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001224 """
1225
Benjamin Peterson59406a92009-03-26 17:10:29 +00001226 _warning_stack_offset = 3
1227
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001228 def __init__(self, raw,
1229 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1230 raw._checkSeekable()
1231 BufferedReader.__init__(self, raw, buffer_size)
1232 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1233
1234 def seek(self, pos, whence=0):
1235 if not (0 <= whence <= 2):
1236 raise ValueError("invalid whence")
1237 self.flush()
1238 if self._read_buf:
1239 # Undo read ahead.
1240 with self._read_lock:
1241 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1242 # First do the raw seek, then empty the read buffer, so that
1243 # if the raw seek fails, we don't lose buffered data forever.
1244 pos = self.raw.seek(pos, whence)
1245 with self._read_lock:
1246 self._reset_read_buf()
1247 if pos < 0:
1248 raise IOError("seek() returned invalid position")
1249 return pos
1250
1251 def tell(self):
1252 if self._write_buf:
1253 return BufferedWriter.tell(self)
1254 else:
1255 return BufferedReader.tell(self)
1256
1257 def truncate(self, pos=None):
1258 if pos is None:
1259 pos = self.tell()
1260 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001261 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001262
1263 def read(self, n=None):
1264 if n is None:
1265 n = -1
1266 self.flush()
1267 return BufferedReader.read(self, n)
1268
1269 def readinto(self, b):
1270 self.flush()
1271 return BufferedReader.readinto(self, b)
1272
1273 def peek(self, n=0):
1274 self.flush()
1275 return BufferedReader.peek(self, n)
1276
1277 def read1(self, n):
1278 self.flush()
1279 return BufferedReader.read1(self, n)
1280
1281 def write(self, b):
1282 if self._read_buf:
1283 # Undo readahead
1284 with self._read_lock:
1285 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1286 self._reset_read_buf()
1287 return BufferedWriter.write(self, b)
1288
1289
1290class TextIOBase(IOBase):
1291
1292 """Base class for text I/O.
1293
1294 This class provides a character and line based interface to stream
1295 I/O. There is no readinto method because Python's character strings
1296 are immutable. There is no public constructor.
1297 """
1298
Georg Brandl4d73b572011-01-13 07:13:06 +00001299 def read(self, n=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001300 """Read at most n characters from stream, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001301
1302 Read from underlying buffer until we have n characters or we hit EOF.
1303 If n is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001304
1305 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001306 """
1307 self._unsupported("read")
1308
Raymond Hettinger3c940242011-01-12 23:39:31 +00001309 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001310 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001311 self._unsupported("write")
1312
Georg Brandl4d73b572011-01-13 07:13:06 +00001313 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001314 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001315 self._unsupported("truncate")
1316
Raymond Hettinger3c940242011-01-12 23:39:31 +00001317 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001318 """Read until newline or EOF.
1319
1320 Returns an empty string if EOF is hit immediately.
1321 """
1322 self._unsupported("readline")
1323
Raymond Hettinger3c940242011-01-12 23:39:31 +00001324 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001325 """
1326 Separate the underlying buffer from the TextIOBase and return it.
1327
1328 After the underlying buffer has been detached, the TextIO is in an
1329 unusable state.
1330 """
1331 self._unsupported("detach")
1332
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001333 @property
1334 def encoding(self):
1335 """Subclasses should override."""
1336 return None
1337
1338 @property
1339 def newlines(self):
1340 """Line endings translated so far.
1341
1342 Only line endings translated during reading are considered.
1343
1344 Subclasses should override.
1345 """
1346 return None
1347
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001348 @property
1349 def errors(self):
1350 """Error setting of the decoder or encoder.
1351
1352 Subclasses should override."""
1353 return None
1354
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001355io.TextIOBase.register(TextIOBase)
1356
1357
1358class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1359 r"""Codec used when reading a file in universal newlines mode. It wraps
1360 another incremental decoder, translating \r\n and \r into \n. It also
1361 records the types of newlines encountered. When used with
1362 translate=False, it ensures that the newline sequence is returned in
1363 one piece.
1364 """
1365 def __init__(self, decoder, translate, errors='strict'):
1366 codecs.IncrementalDecoder.__init__(self, errors=errors)
1367 self.translate = translate
1368 self.decoder = decoder
1369 self.seennl = 0
1370 self.pendingcr = False
1371
1372 def decode(self, input, final=False):
1373 # decode input (with the eventual \r from a previous pass)
1374 if self.decoder is None:
1375 output = input
1376 else:
1377 output = self.decoder.decode(input, final=final)
1378 if self.pendingcr and (output or final):
1379 output = "\r" + output
1380 self.pendingcr = False
1381
1382 # retain last \r even when not translating data:
1383 # then readline() is sure to get \r\n in one pass
1384 if output.endswith("\r") and not final:
1385 output = output[:-1]
1386 self.pendingcr = True
1387
1388 # Record which newlines are read
1389 crlf = output.count('\r\n')
1390 cr = output.count('\r') - crlf
1391 lf = output.count('\n') - crlf
1392 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1393 | (crlf and self._CRLF)
1394
1395 if self.translate:
1396 if crlf:
1397 output = output.replace("\r\n", "\n")
1398 if cr:
1399 output = output.replace("\r", "\n")
1400
1401 return output
1402
1403 def getstate(self):
1404 if self.decoder is None:
1405 buf = b""
1406 flag = 0
1407 else:
1408 buf, flag = self.decoder.getstate()
1409 flag <<= 1
1410 if self.pendingcr:
1411 flag |= 1
1412 return buf, flag
1413
1414 def setstate(self, state):
1415 buf, flag = state
1416 self.pendingcr = bool(flag & 1)
1417 if self.decoder is not None:
1418 self.decoder.setstate((buf, flag >> 1))
1419
1420 def reset(self):
1421 self.seennl = 0
1422 self.pendingcr = False
1423 if self.decoder is not None:
1424 self.decoder.reset()
1425
1426 _LF = 1
1427 _CR = 2
1428 _CRLF = 4
1429
1430 @property
1431 def newlines(self):
1432 return (None,
1433 "\n",
1434 "\r",
1435 ("\r", "\n"),
1436 "\r\n",
1437 ("\n", "\r\n"),
1438 ("\r", "\r\n"),
1439 ("\r", "\n", "\r\n")
1440 )[self.seennl]
1441
1442
1443class TextIOWrapper(TextIOBase):
1444
1445 r"""Character and line based layer over a BufferedIOBase object, buffer.
1446
1447 encoding gives the name of the encoding that the stream will be
1448 decoded or encoded with. It defaults to locale.getpreferredencoding.
1449
1450 errors determines the strictness of encoding and decoding (see the
1451 codecs.register) and defaults to "strict".
1452
1453 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1454 handling of line endings. If it is None, universal newlines is
1455 enabled. With this enabled, on input, the lines endings '\n', '\r',
1456 or '\r\n' are translated to '\n' before being returned to the
1457 caller. Conversely, on output, '\n' is translated to the system
1458 default line seperator, os.linesep. If newline is any other of its
1459 legal values, that newline becomes the newline when the file is read
1460 and it is returned untranslated. On output, '\n' is converted to the
1461 newline.
1462
1463 If line_buffering is True, a call to flush is implied when a call to
1464 write contains a newline character.
1465 """
1466
1467 _CHUNK_SIZE = 2048
1468
1469 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001470 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001471 if newline is not None and not isinstance(newline, str):
1472 raise TypeError("illegal newline type: %r" % (type(newline),))
1473 if newline not in (None, "", "\n", "\r", "\r\n"):
1474 raise ValueError("illegal newline value: %r" % (newline,))
1475 if encoding is None:
1476 try:
1477 encoding = os.device_encoding(buffer.fileno())
1478 except (AttributeError, UnsupportedOperation):
1479 pass
1480 if encoding is None:
1481 try:
1482 import locale
1483 except ImportError:
1484 # Importing locale may fail if Python is being built
1485 encoding = "ascii"
1486 else:
1487 encoding = locale.getpreferredencoding()
1488
1489 if not isinstance(encoding, str):
1490 raise ValueError("invalid encoding: %r" % encoding)
1491
1492 if errors is None:
1493 errors = "strict"
1494 else:
1495 if not isinstance(errors, str):
1496 raise ValueError("invalid errors: %r" % errors)
1497
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001498 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001499 self._line_buffering = line_buffering
1500 self._encoding = encoding
1501 self._errors = errors
1502 self._readuniversal = not newline
1503 self._readtranslate = newline is None
1504 self._readnl = newline
1505 self._writetranslate = newline != ''
1506 self._writenl = newline or os.linesep
1507 self._encoder = None
1508 self._decoder = None
1509 self._decoded_chars = '' # buffer for text returned from decoder
1510 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1511 self._snapshot = None # info for reconstructing decoder state
1512 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001513 self._has_read1 = hasattr(self.buffer, 'read1')
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001514 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001515
Antoine Pitroue4501852009-05-14 18:55:55 +00001516 if self._seekable and self.writable():
1517 position = self.buffer.tell()
1518 if position != 0:
1519 try:
1520 self._get_encoder().setstate(0)
1521 except LookupError:
1522 # Sometimes the encoder doesn't exist
1523 pass
1524
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001525 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1526 # where dec_flags is the second (integer) item of the decoder state
1527 # and next_input is the chunk of input bytes that comes next after the
1528 # snapshot point. We use this to reconstruct decoder states in tell().
1529
1530 # Naming convention:
1531 # - "bytes_..." for integer variables that count input bytes
1532 # - "chars_..." for integer variables that count decoded characters
1533
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001534 def __repr__(self):
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001535 result = "<_pyio.TextIOWrapper"
Antoine Pitrou716c4442009-05-23 19:04:03 +00001536 try:
1537 name = self.name
1538 except AttributeError:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001539 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00001540 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001541 result += " name={0!r}".format(name)
1542 try:
1543 mode = self.mode
1544 except AttributeError:
1545 pass
1546 else:
1547 result += " mode={0!r}".format(mode)
1548 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001549
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001550 @property
1551 def encoding(self):
1552 return self._encoding
1553
1554 @property
1555 def errors(self):
1556 return self._errors
1557
1558 @property
1559 def line_buffering(self):
1560 return self._line_buffering
1561
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001562 @property
1563 def buffer(self):
1564 return self._buffer
1565
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001566 def seekable(self):
1567 return self._seekable
1568
1569 def readable(self):
1570 return self.buffer.readable()
1571
1572 def writable(self):
1573 return self.buffer.writable()
1574
1575 def flush(self):
1576 self.buffer.flush()
1577 self._telling = self._seekable
1578
1579 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00001580 if self.buffer is not None and not self.closed:
1581 self.flush()
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001582 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001583
1584 @property
1585 def closed(self):
1586 return self.buffer.closed
1587
1588 @property
1589 def name(self):
1590 return self.buffer.name
1591
1592 def fileno(self):
1593 return self.buffer.fileno()
1594
1595 def isatty(self):
1596 return self.buffer.isatty()
1597
Raymond Hettinger00fa0392011-01-13 02:52:26 +00001598 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001599 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001600 if self.closed:
1601 raise ValueError("write to closed file")
1602 if not isinstance(s, str):
1603 raise TypeError("can't write %s to text stream" %
1604 s.__class__.__name__)
1605 length = len(s)
1606 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1607 if haslf and self._writetranslate and self._writenl != "\n":
1608 s = s.replace("\n", self._writenl)
1609 encoder = self._encoder or self._get_encoder()
1610 # XXX What if we were just reading?
1611 b = encoder.encode(s)
1612 self.buffer.write(b)
1613 if self._line_buffering and (haslf or "\r" in s):
1614 self.flush()
1615 self._snapshot = None
1616 if self._decoder:
1617 self._decoder.reset()
1618 return length
1619
1620 def _get_encoder(self):
1621 make_encoder = codecs.getincrementalencoder(self._encoding)
1622 self._encoder = make_encoder(self._errors)
1623 return self._encoder
1624
1625 def _get_decoder(self):
1626 make_decoder = codecs.getincrementaldecoder(self._encoding)
1627 decoder = make_decoder(self._errors)
1628 if self._readuniversal:
1629 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1630 self._decoder = decoder
1631 return decoder
1632
1633 # The following three methods implement an ADT for _decoded_chars.
1634 # Text returned from the decoder is buffered here until the client
1635 # requests it by calling our read() or readline() method.
1636 def _set_decoded_chars(self, chars):
1637 """Set the _decoded_chars buffer."""
1638 self._decoded_chars = chars
1639 self._decoded_chars_used = 0
1640
1641 def _get_decoded_chars(self, n=None):
1642 """Advance into the _decoded_chars buffer."""
1643 offset = self._decoded_chars_used
1644 if n is None:
1645 chars = self._decoded_chars[offset:]
1646 else:
1647 chars = self._decoded_chars[offset:offset + n]
1648 self._decoded_chars_used += len(chars)
1649 return chars
1650
1651 def _rewind_decoded_chars(self, n):
1652 """Rewind the _decoded_chars buffer."""
1653 if self._decoded_chars_used < n:
1654 raise AssertionError("rewind decoded_chars out of bounds")
1655 self._decoded_chars_used -= n
1656
1657 def _read_chunk(self):
1658 """
1659 Read and decode the next chunk of data from the BufferedReader.
1660 """
1661
1662 # The return value is True unless EOF was reached. The decoded
1663 # string is placed in self._decoded_chars (replacing its previous
1664 # value). The entire input chunk is sent to the decoder, though
1665 # some of it may remain buffered in the decoder, yet to be
1666 # converted.
1667
1668 if self._decoder is None:
1669 raise ValueError("no decoder")
1670
1671 if self._telling:
1672 # To prepare for tell(), we need to snapshot a point in the
1673 # file where the decoder's input buffer is empty.
1674
1675 dec_buffer, dec_flags = self._decoder.getstate()
1676 # Given this, we know there was a valid snapshot point
1677 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1678
1679 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02001680 if self._has_read1:
1681 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1682 else:
1683 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001684 eof = not input_chunk
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001685 decoded_chars = self._decoder.decode(input_chunk, eof)
1686 self._set_decoded_chars(decoded_chars)
1687 if decoded_chars:
1688 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
1689 else:
1690 self._b2cratio = 0.0
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001691
1692 if self._telling:
1693 # At the snapshot point, len(dec_buffer) bytes before the read,
1694 # the next input to be decoded is dec_buffer + input_chunk.
1695 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1696
1697 return not eof
1698
1699 def _pack_cookie(self, position, dec_flags=0,
1700 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1701 # The meaning of a tell() cookie is: seek to position, set the
1702 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1703 # into the decoder with need_eof as the EOF flag, then skip
1704 # chars_to_skip characters of the decoded result. For most simple
1705 # decoders, tell() will often just give a byte offset in the file.
1706 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1707 (chars_to_skip<<192) | bool(need_eof)<<256)
1708
1709 def _unpack_cookie(self, bigint):
1710 rest, position = divmod(bigint, 1<<64)
1711 rest, dec_flags = divmod(rest, 1<<64)
1712 rest, bytes_to_feed = divmod(rest, 1<<64)
1713 need_eof, chars_to_skip = divmod(rest, 1<<64)
1714 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1715
1716 def tell(self):
1717 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001718 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001719 if not self._telling:
1720 raise IOError("telling position disabled by next() call")
1721 self.flush()
1722 position = self.buffer.tell()
1723 decoder = self._decoder
1724 if decoder is None or self._snapshot is None:
1725 if self._decoded_chars:
1726 # This should never happen.
1727 raise AssertionError("pending decoded text")
1728 return position
1729
1730 # Skip backward to the snapshot point (see _read_chunk).
1731 dec_flags, next_input = self._snapshot
1732 position -= len(next_input)
1733
1734 # How many decoded characters have been used up since the snapshot?
1735 chars_to_skip = self._decoded_chars_used
1736 if chars_to_skip == 0:
1737 # We haven't moved from the snapshot point.
1738 return self._pack_cookie(position, dec_flags)
1739
1740 # Starting from the snapshot position, we will walk the decoder
1741 # forward until it gives us enough decoded characters.
1742 saved_state = decoder.getstate()
1743 try:
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001744 # Fast search for an acceptable start point, close to our
1745 # current pos.
1746 # Rationale: calling decoder.decode() has a large overhead
1747 # regardless of chunk size; we want the number of such calls to
1748 # be O(1) in most situations (common decoders, non-crazy input).
1749 # Actually, it will be exactly 1 for fixed-size codecs (all
1750 # 8-bit codecs, also UTF-16 and UTF-32).
1751 skip_bytes = int(self._b2cratio * chars_to_skip)
1752 skip_back = 1
1753 assert skip_bytes <= len(next_input)
1754 while skip_bytes > 0:
1755 decoder.setstate((b'', dec_flags))
1756 # Decode up to temptative start point
1757 n = len(decoder.decode(next_input[:skip_bytes]))
1758 if n <= chars_to_skip:
1759 b, d = decoder.getstate()
1760 if not b:
1761 # Before pos and no bytes buffered in decoder => OK
1762 dec_flags = d
1763 chars_to_skip -= n
1764 break
1765 # Skip back by buffered amount and reset heuristic
1766 skip_bytes -= len(b)
1767 skip_back = 1
1768 else:
1769 # We're too far ahead, skip back a bit
1770 skip_bytes -= skip_back
1771 skip_back = skip_back * 2
1772 else:
1773 skip_bytes = 0
1774 decoder.setstate((b'', dec_flags))
1775
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001776 # Note our initial start point.
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001777 start_pos = position + skip_bytes
1778 start_flags = dec_flags
1779 if chars_to_skip == 0:
1780 # We haven't moved from the start point.
1781 return self._pack_cookie(start_pos, start_flags)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001782
1783 # Feed the decoder one byte at a time. As we go, note the
1784 # nearest "safe start point" before the current location
1785 # (a point where the decoder has nothing buffered, so seek()
1786 # can safely start from there and advance to this location).
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001787 bytes_fed = 0
1788 need_eof = 0
1789 # Chars decoded since `start_pos`
1790 chars_decoded = 0
1791 for i in range(skip_bytes, len(next_input)):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001792 bytes_fed += 1
Antoine Pitrou211b81d2011-02-25 20:27:33 +00001793 chars_decoded += len(decoder.decode(next_input[i:i+1]))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001794 dec_buffer, dec_flags = decoder.getstate()
1795 if not dec_buffer and chars_decoded <= chars_to_skip:
1796 # Decoder buffer is empty, so this is a safe start point.
1797 start_pos += bytes_fed
1798 chars_to_skip -= chars_decoded
1799 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1800 if chars_decoded >= chars_to_skip:
1801 break
1802 else:
1803 # We didn't get enough decoded data; signal EOF to get more.
1804 chars_decoded += len(decoder.decode(b'', final=True))
1805 need_eof = 1
1806 if chars_decoded < chars_to_skip:
1807 raise IOError("can't reconstruct logical file position")
1808
1809 # The returned cookie corresponds to the last safe start point.
1810 return self._pack_cookie(
1811 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1812 finally:
1813 decoder.setstate(saved_state)
1814
1815 def truncate(self, pos=None):
1816 self.flush()
1817 if pos is None:
1818 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001819 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001820
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001821 def detach(self):
1822 if self.buffer is None:
1823 raise ValueError("buffer is already detached")
1824 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001825 buffer = self._buffer
1826 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001827 return buffer
1828
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001829 def seek(self, cookie, whence=0):
1830 if self.closed:
1831 raise ValueError("tell on closed file")
1832 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001833 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001834 if whence == 1: # seek relative to current position
1835 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001836 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001837 # Seeking to the current position should attempt to
1838 # sync the underlying buffer with the current position.
1839 whence = 0
1840 cookie = self.tell()
1841 if whence == 2: # seek relative to end of file
1842 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001843 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001844 self.flush()
1845 position = self.buffer.seek(0, 2)
1846 self._set_decoded_chars('')
1847 self._snapshot = None
1848 if self._decoder:
1849 self._decoder.reset()
1850 return position
1851 if whence != 0:
1852 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
1853 (whence,))
1854 if cookie < 0:
1855 raise ValueError("negative seek position %r" % (cookie,))
1856 self.flush()
1857
1858 # The strategy of seek() is to go back to the safe start point
1859 # and replay the effect of read(chars_to_skip) from there.
1860 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1861 self._unpack_cookie(cookie)
1862
1863 # Seek back to the safe start point.
1864 self.buffer.seek(start_pos)
1865 self._set_decoded_chars('')
1866 self._snapshot = None
1867
1868 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001869 if cookie == 0 and self._decoder:
1870 self._decoder.reset()
1871 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001872 self._decoder = self._decoder or self._get_decoder()
1873 self._decoder.setstate((b'', dec_flags))
1874 self._snapshot = (dec_flags, b'')
1875
1876 if chars_to_skip:
1877 # Just like _read_chunk, feed the decoder and save a snapshot.
1878 input_chunk = self.buffer.read(bytes_to_feed)
1879 self._set_decoded_chars(
1880 self._decoder.decode(input_chunk, need_eof))
1881 self._snapshot = (dec_flags, input_chunk)
1882
1883 # Skip chars_to_skip of the decoded characters.
1884 if len(self._decoded_chars) < chars_to_skip:
1885 raise IOError("can't restore logical file position")
1886 self._decoded_chars_used = chars_to_skip
1887
Antoine Pitroue4501852009-05-14 18:55:55 +00001888 # Finally, reset the encoder (merely useful for proper BOM handling)
1889 try:
1890 encoder = self._encoder or self._get_encoder()
1891 except LookupError:
1892 # Sometimes the encoder doesn't exist
1893 pass
1894 else:
1895 if cookie != 0:
1896 encoder.setstate(0)
1897 else:
1898 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001899 return cookie
1900
1901 def read(self, n=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00001902 self._checkReadable()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001903 if n is None:
1904 n = -1
1905 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00001906 try:
1907 n.__index__
1908 except AttributeError as err:
1909 raise TypeError("an integer is required") from err
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001910 if n < 0:
1911 # Read everything.
1912 result = (self._get_decoded_chars() +
1913 decoder.decode(self.buffer.read(), final=True))
1914 self._set_decoded_chars('')
1915 self._snapshot = None
1916 return result
1917 else:
1918 # Keep reading chunks until we have n characters to return.
1919 eof = False
1920 result = self._get_decoded_chars(n)
1921 while len(result) < n and not eof:
1922 eof = not self._read_chunk()
1923 result += self._get_decoded_chars(n - len(result))
1924 return result
1925
1926 def __next__(self):
1927 self._telling = False
1928 line = self.readline()
1929 if not line:
1930 self._snapshot = None
1931 self._telling = self._seekable
1932 raise StopIteration
1933 return line
1934
1935 def readline(self, limit=None):
1936 if self.closed:
1937 raise ValueError("read from closed file")
1938 if limit is None:
1939 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +00001940 elif not isinstance(limit, int):
1941 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001942
1943 # Grab all the decoded text (we will rewind any extra bits later).
1944 line = self._get_decoded_chars()
1945
1946 start = 0
1947 # Make the decoder if it doesn't already exist.
1948 if not self._decoder:
1949 self._get_decoder()
1950
1951 pos = endpos = None
1952 while True:
1953 if self._readtranslate:
1954 # Newlines are already translated, only search for \n
1955 pos = line.find('\n', start)
1956 if pos >= 0:
1957 endpos = pos + 1
1958 break
1959 else:
1960 start = len(line)
1961
1962 elif self._readuniversal:
1963 # Universal newline search. Find any of \r, \r\n, \n
1964 # The decoder ensures that \r\n are not split in two pieces
1965
1966 # In C we'd look for these in parallel of course.
1967 nlpos = line.find("\n", start)
1968 crpos = line.find("\r", start)
1969 if crpos == -1:
1970 if nlpos == -1:
1971 # Nothing found
1972 start = len(line)
1973 else:
1974 # Found \n
1975 endpos = nlpos + 1
1976 break
1977 elif nlpos == -1:
1978 # Found lone \r
1979 endpos = crpos + 1
1980 break
1981 elif nlpos < crpos:
1982 # Found \n
1983 endpos = nlpos + 1
1984 break
1985 elif nlpos == crpos + 1:
1986 # Found \r\n
1987 endpos = crpos + 2
1988 break
1989 else:
1990 # Found \r
1991 endpos = crpos + 1
1992 break
1993 else:
1994 # non-universal
1995 pos = line.find(self._readnl)
1996 if pos >= 0:
1997 endpos = pos + len(self._readnl)
1998 break
1999
2000 if limit >= 0 and len(line) >= limit:
2001 endpos = limit # reached length limit
2002 break
2003
2004 # No line ending seen yet - get more data'
2005 while self._read_chunk():
2006 if self._decoded_chars:
2007 break
2008 if self._decoded_chars:
2009 line += self._get_decoded_chars()
2010 else:
2011 # end of file
2012 self._set_decoded_chars('')
2013 self._snapshot = None
2014 return line
2015
2016 if limit >= 0 and endpos > limit:
2017 endpos = limit # don't exceed limit
2018
2019 # Rewind _decoded_chars to just after the line ending we found.
2020 self._rewind_decoded_chars(len(line) - endpos)
2021 return line[:endpos]
2022
2023 @property
2024 def newlines(self):
2025 return self._decoder.newlines if self._decoder else None
2026
2027
2028class StringIO(TextIOWrapper):
2029 """Text I/O implementation using an in-memory buffer.
2030
2031 The initial_value argument sets the value of object. The newline
2032 argument is like the one of TextIOWrapper's constructor.
2033 """
2034
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002035 def __init__(self, initial_value="", newline="\n"):
2036 super(StringIO, self).__init__(BytesIO(),
2037 encoding="utf-8",
2038 errors="strict",
2039 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002040 # Issue #5645: make universal newlines semantics the same as in the
2041 # C version, even under Windows.
2042 if newline is None:
2043 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002044 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002045 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002046 raise TypeError("initial_value must be str or None, not {0}"
2047 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002048 initial_value = str(initial_value)
2049 self.write(initial_value)
2050 self.seek(0)
2051
2052 def getvalue(self):
2053 self.flush()
2054 return self.buffer.getvalue().decode(self._encoding, self._errors)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002055
2056 def __repr__(self):
2057 # TextIOWrapper tells the encoding in its repr. In StringIO,
2058 # that's a implementation detail.
2059 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002060
2061 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002062 def errors(self):
2063 return None
2064
2065 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002066 def encoding(self):
2067 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002068
2069 def detach(self):
2070 # This doesn't make sense on StringIO.
2071 self._unsupported("detach")