blob: a2faeb32579b0b8b2b520a3e48316f18801e8e33 [file] [log] [blame]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001"""
2Python implementation of the io module.
3"""
4
5import os
6import abc
7import codecs
Benjamin Peterson59406a92009-03-26 17:10:29 +00008import warnings
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01009import errno
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000010# Import _thread instead of threading to reduce startup cost
11try:
12 from _thread import allocate_lock as Lock
13except ImportError:
14 from _dummy_thread import allocate_lock as Lock
15
16import io
Benjamin Petersonc3be11a2010-04-27 21:24:03 +000017from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
Antoine Pitroud843c2d2011-02-25 21:34:39 +000018from errno import EINTR
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000019
20# open() uses st_blksize whenever we can
21DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
22
23# NOTE: Base classes defined here are registered with the "official" ABCs
24# defined in io.py. We don't use real inheritance though, because we don't
25# want to inherit the C implementations.
26
27
28class BlockingIOError(IOError):
29
30 """Exception raised when I/O would block on a non-blocking I/O stream."""
31
32 def __init__(self, errno, strerror, characters_written=0):
33 super().__init__(errno, strerror)
34 if not isinstance(characters_written, int):
35 raise TypeError("characters_written must be a integer")
36 self.characters_written = characters_written
37
38
Georg Brandl4d73b572011-01-13 07:13:06 +000039def open(file, mode="r", buffering=-1, encoding=None, errors=None,
40 newline=None, closefd=True):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000041
42 r"""Open file and return a stream. Raise IOError upon failure.
43
44 file is either a text or byte string giving the name (and the path
45 if the file isn't in the current working directory) of the file to
46 be opened or an integer file descriptor of the file to be
47 wrapped. (If a file descriptor is given, it is closed when the
48 returned I/O object is closed, unless closefd is set to False.)
49
50 mode is an optional string that specifies the mode in which the file
51 is opened. It defaults to 'r' which means open for reading in text
52 mode. Other common values are 'w' for writing (truncating the file if
53 it already exists), and 'a' for appending (which on some Unix systems,
54 means that all writes append to the end of the file regardless of the
55 current seek position). In text mode, if encoding is not specified the
56 encoding used is platform dependent. (For reading and writing raw
57 bytes use binary mode and leave encoding unspecified.) The available
58 modes are:
59
60 ========= ===============================================================
61 Character Meaning
62 --------- ---------------------------------------------------------------
63 'r' open for reading (default)
64 'w' open for writing, truncating the file first
65 'a' open for writing, appending to the end of the file if it exists
66 'b' binary mode
67 't' text mode (default)
68 '+' open a disk file for updating (reading and writing)
69 'U' universal newline mode (for backwards compatibility; unneeded
70 for new code)
71 ========= ===============================================================
72
73 The default mode is 'rt' (open for reading text). For binary random
74 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
75 'r+b' opens the file without truncation.
76
77 Python distinguishes between files opened in binary and text modes,
78 even when the underlying operating system doesn't. Files opened in
79 binary mode (appending 'b' to the mode argument) return contents as
80 bytes objects without any decoding. In text mode (the default, or when
81 't' is appended to the mode argument), the contents of the file are
82 returned as strings, the bytes having been first decoded using a
83 platform-dependent encoding or using the specified encoding if given.
84
Antoine Pitroud5587bc2009-12-19 21:08:31 +000085 buffering is an optional integer used to set the buffering policy.
86 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
87 line buffering (only usable in text mode), and an integer > 1 to indicate
88 the size of a fixed-size chunk buffer. When no buffering argument is
89 given, the default buffering policy works as follows:
90
91 * Binary files are buffered in fixed-size chunks; the size of the buffer
92 is chosen using a heuristic trying to determine the underlying device's
93 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
94 On many systems, the buffer will typically be 4096 or 8192 bytes long.
95
96 * "Interactive" text files (files for which isatty() returns True)
97 use line buffering. Other text files use the policy described above
98 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000099
Raymond Hettingercbb80892011-01-13 18:15:51 +0000100 encoding is the str name of the encoding used to decode or encode the
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000101 file. This should only be used in text mode. The default encoding is
102 platform dependent, but any encoding supported by Python can be
103 passed. See the codecs module for the list of supported encodings.
104
105 errors is an optional string that specifies how encoding errors are to
106 be handled---this argument should not be used in binary mode. Pass
107 'strict' to raise a ValueError exception if there is an encoding error
108 (the default of None has the same effect), or pass 'ignore' to ignore
109 errors. (Note that ignoring encoding errors can lead to data loss.)
110 See the documentation for codecs.register for a list of the permitted
111 encoding error strings.
112
Raymond Hettingercbb80892011-01-13 18:15:51 +0000113 newline is a string controlling how universal newlines works (it only
114 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
115 as follows:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000116
117 * On input, if newline is None, universal newlines mode is
118 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
119 these are translated into '\n' before being returned to the
120 caller. If it is '', universal newline mode is enabled, but line
121 endings are returned to the caller untranslated. If it has any of
122 the other legal values, input lines are only terminated by the given
123 string, and the line ending is returned to the caller untranslated.
124
125 * On output, if newline is None, any '\n' characters written are
126 translated to the system default line separator, os.linesep. If
127 newline is '', no translation takes place. If newline is any of the
128 other legal values, any '\n' characters written are translated to
129 the given string.
130
Raymond Hettingercbb80892011-01-13 18:15:51 +0000131 closedfd is a bool. If closefd is False, the underlying file descriptor will
132 be kept open when the file is closed. This does not work when a file name is
133 given and must be True in that case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000134
135 open() returns a file object whose type depends on the mode, and
136 through which the standard file operations such as reading and writing
137 are performed. When open() is used to open a file in a text mode ('w',
138 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
139 a file in a binary mode, the returned class varies: in read binary
140 mode, it returns a BufferedReader; in write binary and append binary
141 modes, it returns a BufferedWriter, and in read/write mode, it returns
142 a BufferedRandom.
143
144 It is also possible to use a string or bytearray as a file for both
145 reading and writing. For strings StringIO can be used like a file
146 opened in a text mode, and for bytes a BytesIO can be used like a file
147 opened in a binary mode.
148 """
149 if not isinstance(file, (str, bytes, int)):
150 raise TypeError("invalid file: %r" % file)
151 if not isinstance(mode, str):
152 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000153 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000154 raise TypeError("invalid buffering: %r" % buffering)
155 if encoding is not None and not isinstance(encoding, str):
156 raise TypeError("invalid encoding: %r" % encoding)
157 if errors is not None and not isinstance(errors, str):
158 raise TypeError("invalid errors: %r" % errors)
159 modes = set(mode)
160 if modes - set("arwb+tU") or len(mode) > len(modes):
161 raise ValueError("invalid mode: %r" % mode)
162 reading = "r" in modes
163 writing = "w" in modes
164 appending = "a" in modes
165 updating = "+" in modes
166 text = "t" in modes
167 binary = "b" in modes
168 if "U" in modes:
169 if writing or appending:
170 raise ValueError("can't use U and writing mode at once")
171 reading = True
172 if text and binary:
173 raise ValueError("can't have text and binary mode at once")
174 if reading + writing + appending > 1:
175 raise ValueError("can't have read/write/append mode at once")
176 if not (reading or writing or appending):
177 raise ValueError("must have exactly one of read/write/append mode")
178 if binary and encoding is not None:
179 raise ValueError("binary mode doesn't take an encoding argument")
180 if binary and errors is not None:
181 raise ValueError("binary mode doesn't take an errors argument")
182 if binary and newline is not None:
183 raise ValueError("binary mode doesn't take a newline argument")
184 raw = FileIO(file,
185 (reading and "r" or "") +
186 (writing and "w" or "") +
187 (appending and "a" or "") +
188 (updating and "+" or ""),
189 closefd)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000190 line_buffering = False
191 if buffering == 1 or buffering < 0 and raw.isatty():
192 buffering = -1
193 line_buffering = True
194 if buffering < 0:
195 buffering = DEFAULT_BUFFER_SIZE
196 try:
197 bs = os.fstat(raw.fileno()).st_blksize
198 except (os.error, AttributeError):
199 pass
200 else:
201 if bs > 1:
202 buffering = bs
203 if buffering < 0:
204 raise ValueError("invalid buffering size")
205 if buffering == 0:
206 if binary:
207 return raw
208 raise ValueError("can't have unbuffered text I/O")
209 if updating:
210 buffer = BufferedRandom(raw, buffering)
211 elif writing or appending:
212 buffer = BufferedWriter(raw, buffering)
213 elif reading:
214 buffer = BufferedReader(raw, buffering)
215 else:
216 raise ValueError("unknown mode: %r" % mode)
217 if binary:
218 return buffer
219 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
220 text.mode = mode
221 return text
222
223
224class DocDescriptor:
225 """Helper for builtins.open.__doc__
226 """
227 def __get__(self, obj, typ):
228 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000229 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000230 "errors=None, newline=None, closefd=True)\n\n" +
231 open.__doc__)
232
233class OpenWrapper:
234 """Wrapper for builtins.open
235
236 Trick so that open won't become a bound method when stored
237 as a class variable (as dbm.dumb does).
238
239 See initstdio() in Python/pythonrun.c.
240 """
241 __doc__ = DocDescriptor()
242
243 def __new__(cls, *args, **kwargs):
244 return open(*args, **kwargs)
245
246
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000247# In normal operation, both `UnsupportedOperation`s should be bound to the
248# same object.
249try:
250 UnsupportedOperation = io.UnsupportedOperation
251except AttributeError:
252 class UnsupportedOperation(ValueError, IOError):
253 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000254
255
256class IOBase(metaclass=abc.ABCMeta):
257
258 """The abstract base class for all I/O classes, acting on streams of
259 bytes. There is no public constructor.
260
261 This class provides dummy implementations for many methods that
262 derived classes can override selectively; the default implementations
263 represent a file that cannot be read, written or seeked.
264
265 Even though IOBase does not declare read, readinto, or write because
266 their signatures will vary, implementations and clients should
267 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000268 may raise UnsupportedOperation when operations they do not support are
269 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000270
271 The basic type used for binary data read from or written to a file is
272 bytes. bytearrays are accepted too, and in some cases (such as
273 readinto) needed. Text I/O classes work with str data.
274
275 Note that calling any method (even inquiries) on a closed stream is
276 undefined. Implementations may raise IOError in this case.
277
278 IOBase (and its subclasses) support the iterator protocol, meaning
279 that an IOBase object can be iterated over yielding the lines in a
280 stream.
281
282 IOBase also supports the :keyword:`with` statement. In this example,
283 fp is closed after the suite of the with statement is complete:
284
285 with open('spam.txt', 'r') as fp:
286 fp.write('Spam and eggs!')
287 """
288
289 ### Internal ###
290
Raymond Hettinger3c940242011-01-12 23:39:31 +0000291 def _unsupported(self, name):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000292 """Internal: raise an IOError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000293 raise UnsupportedOperation("%s.%s() not supported" %
294 (self.__class__.__name__, name))
295
296 ### Positioning ###
297
Georg Brandl4d73b572011-01-13 07:13:06 +0000298 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000299 """Change stream position.
300
301 Change the stream position to byte offset offset. offset is
302 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000303 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000304
305 * 0 -- start of stream (the default); offset should be zero or positive
306 * 1 -- current stream position; offset may be negative
307 * 2 -- end of stream; offset is usually negative
308
Raymond Hettingercbb80892011-01-13 18:15:51 +0000309 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000310 """
311 self._unsupported("seek")
312
Raymond Hettinger3c940242011-01-12 23:39:31 +0000313 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000314 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000315 return self.seek(0, 1)
316
Georg Brandl4d73b572011-01-13 07:13:06 +0000317 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000318 """Truncate file to size bytes.
319
320 Size defaults to the current IO position as reported by tell(). Return
321 the new size.
322 """
323 self._unsupported("truncate")
324
325 ### Flush and close ###
326
Raymond Hettinger3c940242011-01-12 23:39:31 +0000327 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000328 """Flush write buffers, if applicable.
329
330 This is not implemented for read-only and non-blocking streams.
331 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000332 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000333 # XXX Should this return the number of bytes written???
334
335 __closed = False
336
Raymond Hettinger3c940242011-01-12 23:39:31 +0000337 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000338 """Flush and close the IO object.
339
340 This method has no effect if the file is already closed.
341 """
342 if not self.__closed:
Antoine Pitrou6be88762010-05-03 16:48:20 +0000343 self.flush()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000344 self.__closed = True
345
Raymond Hettinger3c940242011-01-12 23:39:31 +0000346 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000347 """Destructor. Calls close()."""
348 # The try/except block is in case this is called at program
349 # exit time, when it's possible that globals have already been
350 # deleted, and then the close() call might fail. Since
351 # there's nothing we can do about such failures and they annoy
352 # the end users, we suppress the traceback.
353 try:
354 self.close()
355 except:
356 pass
357
358 ### Inquiries ###
359
Raymond Hettinger3c940242011-01-12 23:39:31 +0000360 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000361 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000362
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000363 If False, seek(), tell() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000364 This method may need to do a test seek().
365 """
366 return False
367
368 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000369 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000370 """
371 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000372 raise UnsupportedOperation("File or stream is not seekable."
373 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000374
Raymond Hettinger3c940242011-01-12 23:39:31 +0000375 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000376 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000377
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000378 If False, read() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000379 """
380 return False
381
382 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000383 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000384 """
385 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000386 raise UnsupportedOperation("File or stream is not readable."
387 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000388
Raymond Hettinger3c940242011-01-12 23:39:31 +0000389 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000390 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000391
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000392 If False, write() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000393 """
394 return False
395
396 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000397 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000398 """
399 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000400 raise UnsupportedOperation("File or stream is not writable."
401 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000402
403 @property
404 def closed(self):
405 """closed: bool. True iff the file has been closed.
406
407 For backwards compatibility, this is a property, not a predicate.
408 """
409 return self.__closed
410
411 def _checkClosed(self, msg=None):
412 """Internal: raise an ValueError if file is closed
413 """
414 if self.closed:
415 raise ValueError("I/O operation on closed file."
416 if msg is None else msg)
417
418 ### Context manager ###
419
Raymond Hettinger3c940242011-01-12 23:39:31 +0000420 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000421 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000422 self._checkClosed()
423 return self
424
Raymond Hettinger3c940242011-01-12 23:39:31 +0000425 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000426 """Context management protocol. Calls close()"""
427 self.close()
428
429 ### Lower-level APIs ###
430
431 # XXX Should these be present even if unimplemented?
432
Raymond Hettinger3c940242011-01-12 23:39:31 +0000433 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000434 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000435
436 An IOError is raised if the IO object does not use a file descriptor.
437 """
438 self._unsupported("fileno")
439
Raymond Hettinger3c940242011-01-12 23:39:31 +0000440 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000441 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000442
443 Return False if it can't be determined.
444 """
445 self._checkClosed()
446 return False
447
448 ### Readline[s] and writelines ###
449
Georg Brandl4d73b572011-01-13 07:13:06 +0000450 def readline(self, limit=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000451 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000452
453 If limit is specified, at most limit bytes will be read.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000454 Limit should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000455
456 The line terminator is always b'\n' for binary files; for text
457 files, the newlines argument to open can be used to select the line
458 terminator(s) recognized.
459 """
460 # For backwards compatibility, a (slowish) readline().
461 if hasattr(self, "peek"):
462 def nreadahead():
463 readahead = self.peek(1)
464 if not readahead:
465 return 1
466 n = (readahead.find(b"\n") + 1) or len(readahead)
467 if limit >= 0:
468 n = min(n, limit)
469 return n
470 else:
471 def nreadahead():
472 return 1
473 if limit is None:
474 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +0000475 elif not isinstance(limit, int):
476 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000477 res = bytearray()
478 while limit < 0 or len(res) < limit:
479 b = self.read(nreadahead())
480 if not b:
481 break
482 res += b
483 if res.endswith(b"\n"):
484 break
485 return bytes(res)
486
487 def __iter__(self):
488 self._checkClosed()
489 return self
490
491 def __next__(self):
492 line = self.readline()
493 if not line:
494 raise StopIteration
495 return line
496
497 def readlines(self, hint=None):
498 """Return a list of lines from the stream.
499
500 hint can be specified to control the number of lines read: no more
501 lines will be read if the total size (in bytes/characters) of all
502 lines so far exceeds hint.
503 """
504 if hint is None or hint <= 0:
505 return list(self)
506 n = 0
507 lines = []
508 for line in self:
509 lines.append(line)
510 n += len(line)
511 if n >= hint:
512 break
513 return lines
514
515 def writelines(self, lines):
516 self._checkClosed()
517 for line in lines:
518 self.write(line)
519
520io.IOBase.register(IOBase)
521
522
523class RawIOBase(IOBase):
524
525 """Base class for raw binary I/O."""
526
527 # The read() method is implemented by calling readinto(); derived
528 # classes that want to support read() only need to implement
529 # readinto() as a primitive operation. In general, readinto() can be
530 # more efficient than read().
531
532 # (It would be tempting to also provide an implementation of
533 # readinto() in terms of read(), in case the latter is a more suitable
534 # primitive operation, but that would lead to nasty recursion in case
535 # a subclass doesn't implement either.)
536
Georg Brandl4d73b572011-01-13 07:13:06 +0000537 def read(self, n=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000538 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000539
540 Returns an empty bytes object on EOF, or None if the object is
541 set not to block and has no data to read.
542 """
543 if n is None:
544 n = -1
545 if n < 0:
546 return self.readall()
547 b = bytearray(n.__index__())
548 n = self.readinto(b)
Antoine Pitrou328ec742010-09-14 18:37:24 +0000549 if n is None:
550 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000551 del b[n:]
552 return bytes(b)
553
554 def readall(self):
555 """Read until EOF, using multiple read() call."""
556 res = bytearray()
557 while True:
558 data = self.read(DEFAULT_BUFFER_SIZE)
559 if not data:
560 break
561 res += data
Victor Stinnera80987f2011-05-25 22:47:16 +0200562 if res:
563 return bytes(res)
564 else:
565 # b'' or None
566 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000567
Raymond Hettinger3c940242011-01-12 23:39:31 +0000568 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000569 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000570
Raymond Hettingercbb80892011-01-13 18:15:51 +0000571 Returns an int representing the number of bytes read (0 for EOF), or
572 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000573 """
574 self._unsupported("readinto")
575
Raymond Hettinger3c940242011-01-12 23:39:31 +0000576 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000577 """Write the given buffer to the IO stream.
578
579 Returns the number of bytes written, which may be less than len(b).
580 """
581 self._unsupported("write")
582
583io.RawIOBase.register(RawIOBase)
584from _io import FileIO
585RawIOBase.register(FileIO)
586
587
588class BufferedIOBase(IOBase):
589
590 """Base class for buffered IO objects.
591
592 The main difference with RawIOBase is that the read() method
593 supports omitting the size argument, and does not have a default
594 implementation that defers to readinto().
595
596 In addition, read(), readinto() and write() may raise
597 BlockingIOError if the underlying raw stream is in non-blocking
598 mode and not ready; unlike their raw counterparts, they will never
599 return None.
600
601 A typical implementation should not inherit from a RawIOBase
602 implementation, but wrap one.
603 """
604
Georg Brandl4d73b572011-01-13 07:13:06 +0000605 def read(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000606 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000607
608 If the argument is omitted, None, or negative, reads and
609 returns all data until EOF.
610
611 If the argument is positive, and the underlying raw stream is
612 not 'interactive', multiple raw reads may be issued to satisfy
613 the byte count (unless EOF is reached first). But for
614 interactive raw streams (XXX and for pipes?), at most one raw
615 read will be issued, and a short result does not imply that
616 EOF is imminent.
617
618 Returns an empty bytes array on EOF.
619
620 Raises BlockingIOError if the underlying raw stream has no
621 data at the moment.
622 """
623 self._unsupported("read")
624
Georg Brandl4d73b572011-01-13 07:13:06 +0000625 def read1(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000626 """Read up to n bytes with at most one read() system call,
627 where n is an int.
628 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000629 self._unsupported("read1")
630
Raymond Hettinger3c940242011-01-12 23:39:31 +0000631 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000632 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000633
634 Like read(), this may issue multiple reads to the underlying raw
635 stream, unless the latter is 'interactive'.
636
Raymond Hettingercbb80892011-01-13 18:15:51 +0000637 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000638
639 Raises BlockingIOError if the underlying raw stream has no
640 data at the moment.
641 """
642 # XXX This ought to work with anything that supports the buffer API
643 data = self.read(len(b))
644 n = len(data)
645 try:
646 b[:n] = data
647 except TypeError as err:
648 import array
649 if not isinstance(b, array.array):
650 raise err
651 b[:n] = array.array('b', data)
652 return n
653
Raymond Hettinger3c940242011-01-12 23:39:31 +0000654 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000655 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000656
657 Return the number of bytes written, which is never less than
658 len(b).
659
660 Raises BlockingIOError if the buffer is full and the
661 underlying raw stream cannot accept more data at the moment.
662 """
663 self._unsupported("write")
664
Raymond Hettinger3c940242011-01-12 23:39:31 +0000665 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000666 """
667 Separate the underlying raw stream from the buffer and return it.
668
669 After the raw stream has been detached, the buffer is in an unusable
670 state.
671 """
672 self._unsupported("detach")
673
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000674io.BufferedIOBase.register(BufferedIOBase)
675
676
677class _BufferedIOMixin(BufferedIOBase):
678
679 """A mixin implementation of BufferedIOBase with an underlying raw stream.
680
681 This passes most requests on to the underlying raw stream. It
682 does *not* provide implementations of read(), readinto() or
683 write().
684 """
685
686 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000687 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000688
689 ### Positioning ###
690
691 def seek(self, pos, whence=0):
692 new_position = self.raw.seek(pos, whence)
693 if new_position < 0:
694 raise IOError("seek() returned an invalid position")
695 return new_position
696
697 def tell(self):
698 pos = self.raw.tell()
699 if pos < 0:
700 raise IOError("tell() returned an invalid position")
701 return pos
702
703 def truncate(self, pos=None):
704 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
705 # and a flush may be necessary to synch both views of the current
706 # file state.
707 self.flush()
708
709 if pos is None:
710 pos = self.tell()
711 # XXX: Should seek() be used, instead of passing the position
712 # XXX directly to truncate?
713 return self.raw.truncate(pos)
714
715 ### Flush and close ###
716
717 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000718 if self.closed:
719 raise ValueError("flush of closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000720 self.raw.flush()
721
722 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000723 if self.raw is not None and not self.closed:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +0100724 try:
725 # may raise BlockingIOError or BrokenPipeError etc
726 self.flush()
727 finally:
728 self.raw.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000729
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000730 def detach(self):
731 if self.raw is None:
732 raise ValueError("raw stream already detached")
733 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000734 raw = self._raw
735 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000736 return raw
737
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000738 ### Inquiries ###
739
740 def seekable(self):
741 return self.raw.seekable()
742
743 def readable(self):
744 return self.raw.readable()
745
746 def writable(self):
747 return self.raw.writable()
748
749 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000750 def raw(self):
751 return self._raw
752
753 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000754 def closed(self):
755 return self.raw.closed
756
757 @property
758 def name(self):
759 return self.raw.name
760
761 @property
762 def mode(self):
763 return self.raw.mode
764
Antoine Pitrou243757e2010-11-05 21:15:39 +0000765 def __getstate__(self):
766 raise TypeError("can not serialize a '{0}' object"
767 .format(self.__class__.__name__))
768
Antoine Pitrou716c4442009-05-23 19:04:03 +0000769 def __repr__(self):
770 clsname = self.__class__.__name__
771 try:
772 name = self.name
773 except AttributeError:
774 return "<_pyio.{0}>".format(clsname)
775 else:
776 return "<_pyio.{0} name={1!r}>".format(clsname, name)
777
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000778 ### Lower-level APIs ###
779
780 def fileno(self):
781 return self.raw.fileno()
782
783 def isatty(self):
784 return self.raw.isatty()
785
786
787class BytesIO(BufferedIOBase):
788
789 """Buffered I/O implementation using an in-memory bytes buffer."""
790
791 def __init__(self, initial_bytes=None):
792 buf = bytearray()
793 if initial_bytes is not None:
794 buf += initial_bytes
795 self._buffer = buf
796 self._pos = 0
797
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000798 def __getstate__(self):
799 if self.closed:
800 raise ValueError("__getstate__ on closed file")
801 return self.__dict__.copy()
802
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000803 def getvalue(self):
804 """Return the bytes value (contents) of the buffer
805 """
806 if self.closed:
807 raise ValueError("getvalue on closed file")
808 return bytes(self._buffer)
809
Antoine Pitrou972ee132010-09-06 18:48:21 +0000810 def getbuffer(self):
811 """Return a readable and writable view of the buffer.
812 """
813 return memoryview(self._buffer)
814
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000815 def read(self, n=None):
816 if self.closed:
817 raise ValueError("read from closed file")
818 if n is None:
819 n = -1
820 if n < 0:
821 n = len(self._buffer)
822 if len(self._buffer) <= self._pos:
823 return b""
824 newpos = min(len(self._buffer), self._pos + n)
825 b = self._buffer[self._pos : newpos]
826 self._pos = newpos
827 return bytes(b)
828
829 def read1(self, n):
830 """This is the same as read.
831 """
832 return self.read(n)
833
834 def write(self, b):
835 if self.closed:
836 raise ValueError("write to closed file")
837 if isinstance(b, str):
838 raise TypeError("can't write str to binary stream")
839 n = len(b)
840 if n == 0:
841 return 0
842 pos = self._pos
843 if pos > len(self._buffer):
844 # Inserts null bytes between the current end of the file
845 # and the new write position.
846 padding = b'\x00' * (pos - len(self._buffer))
847 self._buffer += padding
848 self._buffer[pos:pos + n] = b
849 self._pos += n
850 return n
851
852 def seek(self, pos, whence=0):
853 if self.closed:
854 raise ValueError("seek on closed file")
855 try:
Florent Xiclunab14930c2010-03-13 15:26:44 +0000856 pos.__index__
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000857 except AttributeError as err:
858 raise TypeError("an integer is required") from err
859 if whence == 0:
860 if pos < 0:
861 raise ValueError("negative seek position %r" % (pos,))
862 self._pos = pos
863 elif whence == 1:
864 self._pos = max(0, self._pos + pos)
865 elif whence == 2:
866 self._pos = max(0, len(self._buffer) + pos)
867 else:
868 raise ValueError("invalid whence value")
869 return self._pos
870
871 def tell(self):
872 if self.closed:
873 raise ValueError("tell on closed file")
874 return self._pos
875
876 def truncate(self, pos=None):
877 if self.closed:
878 raise ValueError("truncate on closed file")
879 if pos is None:
880 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000881 else:
882 try:
883 pos.__index__
884 except AttributeError as err:
885 raise TypeError("an integer is required") from err
886 if pos < 0:
887 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000888 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000889 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000890
891 def readable(self):
892 return True
893
894 def writable(self):
895 return True
896
897 def seekable(self):
898 return True
899
900
901class BufferedReader(_BufferedIOMixin):
902
903 """BufferedReader(raw[, buffer_size])
904
905 A buffer for a readable, sequential BaseRawIO object.
906
907 The constructor creates a BufferedReader for the given readable raw
908 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
909 is used.
910 """
911
912 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
913 """Create a new buffered reader using the given readable raw IO object.
914 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000915 if not raw.readable():
916 raise IOError('"raw" argument must be readable.')
917
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000918 _BufferedIOMixin.__init__(self, raw)
919 if buffer_size <= 0:
920 raise ValueError("invalid buffer size")
921 self.buffer_size = buffer_size
922 self._reset_read_buf()
923 self._read_lock = Lock()
924
925 def _reset_read_buf(self):
926 self._read_buf = b""
927 self._read_pos = 0
928
929 def read(self, n=None):
930 """Read n bytes.
931
932 Returns exactly n bytes of data unless the underlying raw IO
933 stream reaches EOF or if the call would block in non-blocking
934 mode. If n is negative, read until EOF or until read() would
935 block.
936 """
937 if n is not None and n < -1:
938 raise ValueError("invalid number of bytes to read")
939 with self._read_lock:
940 return self._read_unlocked(n)
941
942 def _read_unlocked(self, n=None):
943 nodata_val = b""
944 empty_values = (b"", None)
945 buf = self._read_buf
946 pos = self._read_pos
947
948 # Special case for when the number of bytes to read is unspecified.
949 if n is None or n == -1:
950 self._reset_read_buf()
951 chunks = [buf[pos:]] # Strip the consumed bytes.
952 current_size = 0
953 while True:
954 # Read until EOF or until read() would block.
Antoine Pitroud843c2d2011-02-25 21:34:39 +0000955 try:
956 chunk = self.raw.read()
957 except IOError as e:
958 if e.errno != EINTR:
959 raise
960 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000961 if chunk in empty_values:
962 nodata_val = chunk
963 break
964 current_size += len(chunk)
965 chunks.append(chunk)
966 return b"".join(chunks) or nodata_val
967
968 # The number of bytes to read is specified, return at most n bytes.
969 avail = len(buf) - pos # Length of the available buffered data.
970 if n <= avail:
971 # Fast path: the data to read is fully buffered.
972 self._read_pos += n
973 return buf[pos:pos+n]
974 # Slow path: read from the stream until enough bytes are read,
975 # or until an EOF occurs or until read() would block.
976 chunks = [buf[pos:]]
977 wanted = max(self.buffer_size, n)
978 while avail < n:
Antoine Pitroud843c2d2011-02-25 21:34:39 +0000979 try:
980 chunk = self.raw.read(wanted)
981 except IOError as e:
982 if e.errno != EINTR:
983 raise
984 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000985 if chunk in empty_values:
986 nodata_val = chunk
987 break
988 avail += len(chunk)
989 chunks.append(chunk)
990 # n is more then avail only when an EOF occurred or when
991 # read() would have blocked.
992 n = min(n, avail)
993 out = b"".join(chunks)
994 self._read_buf = out[n:] # Save the extra data in the buffer.
995 self._read_pos = 0
996 return out[:n] if out else nodata_val
997
998 def peek(self, n=0):
999 """Returns buffered bytes without advancing the position.
1000
1001 The argument indicates a desired minimal number of bytes; we
1002 do at most one raw read to satisfy it. We never return more
1003 than self.buffer_size.
1004 """
1005 with self._read_lock:
1006 return self._peek_unlocked(n)
1007
1008 def _peek_unlocked(self, n=0):
1009 want = min(n, self.buffer_size)
1010 have = len(self._read_buf) - self._read_pos
1011 if have < want or have <= 0:
1012 to_read = self.buffer_size - have
Antoine Pitroud843c2d2011-02-25 21:34:39 +00001013 while True:
1014 try:
1015 current = self.raw.read(to_read)
1016 except IOError as e:
1017 if e.errno != EINTR:
1018 raise
1019 continue
1020 break
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001021 if current:
1022 self._read_buf = self._read_buf[self._read_pos:] + current
1023 self._read_pos = 0
1024 return self._read_buf[self._read_pos:]
1025
1026 def read1(self, n):
1027 """Reads up to n bytes, with at most one read() system call."""
1028 # Returns up to n bytes. If at least one byte is buffered, we
1029 # only return buffered bytes. Otherwise, we do one raw read.
1030 if n < 0:
1031 raise ValueError("number of bytes to read must be positive")
1032 if n == 0:
1033 return b""
1034 with self._read_lock:
1035 self._peek_unlocked(1)
1036 return self._read_unlocked(
1037 min(n, len(self._read_buf) - self._read_pos))
1038
1039 def tell(self):
1040 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1041
1042 def seek(self, pos, whence=0):
1043 if not (0 <= whence <= 2):
1044 raise ValueError("invalid whence value")
1045 with self._read_lock:
1046 if whence == 1:
1047 pos -= len(self._read_buf) - self._read_pos
1048 pos = _BufferedIOMixin.seek(self, pos, whence)
1049 self._reset_read_buf()
1050 return pos
1051
1052class BufferedWriter(_BufferedIOMixin):
1053
1054 """A buffer for a writeable sequential RawIO object.
1055
1056 The constructor creates a BufferedWriter for the given writeable raw
1057 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001058 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001059 """
1060
Benjamin Peterson59406a92009-03-26 17:10:29 +00001061 _warning_stack_offset = 2
1062
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001063 def __init__(self, raw,
1064 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001065 if not raw.writable():
1066 raise IOError('"raw" argument must be writable.')
1067
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001068 _BufferedIOMixin.__init__(self, raw)
1069 if buffer_size <= 0:
1070 raise ValueError("invalid buffer size")
Benjamin Peterson59406a92009-03-26 17:10:29 +00001071 if max_buffer_size is not None:
1072 warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
1073 self._warning_stack_offset)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001074 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001075 self._write_buf = bytearray()
1076 self._write_lock = Lock()
1077
1078 def write(self, b):
1079 if self.closed:
1080 raise ValueError("write to closed file")
1081 if isinstance(b, str):
1082 raise TypeError("can't write str to binary stream")
1083 with self._write_lock:
1084 # XXX we can implement some more tricks to try and avoid
1085 # partial writes
1086 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001087 # We're full, so let's pre-flush the buffer. (This may
1088 # raise BlockingIOError with characters_written == 0.)
1089 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001090 before = len(self._write_buf)
1091 self._write_buf.extend(b)
1092 written = len(self._write_buf) - before
1093 if len(self._write_buf) > self.buffer_size:
1094 try:
1095 self._flush_unlocked()
1096 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001097 if len(self._write_buf) > self.buffer_size:
1098 # We've hit the buffer_size. We have to accept a partial
1099 # write and cut back our buffer.
1100 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001101 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001102 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001103 raise BlockingIOError(e.errno, e.strerror, written)
1104 return written
1105
1106 def truncate(self, pos=None):
1107 with self._write_lock:
1108 self._flush_unlocked()
1109 if pos is None:
1110 pos = self.raw.tell()
1111 return self.raw.truncate(pos)
1112
1113 def flush(self):
1114 with self._write_lock:
1115 self._flush_unlocked()
1116
1117 def _flush_unlocked(self):
1118 if self.closed:
1119 raise ValueError("flush of closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001120 while self._write_buf:
1121 try:
1122 n = self.raw.write(self._write_buf)
1123 except BlockingIOError:
1124 raise RuntimeError("self.raw should implement RawIOBase: it "
1125 "should not raise BlockingIOError")
1126 except IOError as e:
1127 if e.errno != EINTR:
1128 raise
1129 continue
1130 if n is None:
1131 raise BlockingIOError(
1132 errno.EAGAIN,
1133 "write could not complete without blocking", 0)
1134 if n > len(self._write_buf) or n < 0:
1135 raise IOError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001136 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001137
1138 def tell(self):
1139 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1140
1141 def seek(self, pos, whence=0):
1142 if not (0 <= whence <= 2):
1143 raise ValueError("invalid whence")
1144 with self._write_lock:
1145 self._flush_unlocked()
1146 return _BufferedIOMixin.seek(self, pos, whence)
1147
1148
1149class BufferedRWPair(BufferedIOBase):
1150
1151 """A buffered reader and writer object together.
1152
1153 A buffered reader object and buffered writer object put together to
1154 form a sequential IO object that can read and write. This is typically
1155 used with a socket or two-way pipe.
1156
1157 reader and writer are RawIOBase objects that are readable and
1158 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001159 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001160 """
1161
1162 # XXX The usefulness of this (compared to having two separate IO
1163 # objects) is questionable.
1164
1165 def __init__(self, reader, writer,
1166 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1167 """Constructor.
1168
1169 The arguments are two RawIO instances.
1170 """
Benjamin Peterson59406a92009-03-26 17:10:29 +00001171 if max_buffer_size is not None:
1172 warnings.warn("max_buffer_size is deprecated", DeprecationWarning, 2)
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001173
1174 if not reader.readable():
1175 raise IOError('"reader" argument must be readable.')
1176
1177 if not writer.writable():
1178 raise IOError('"writer" argument must be writable.')
1179
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001180 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001181 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001182
1183 def read(self, n=None):
1184 if n is None:
1185 n = -1
1186 return self.reader.read(n)
1187
1188 def readinto(self, b):
1189 return self.reader.readinto(b)
1190
1191 def write(self, b):
1192 return self.writer.write(b)
1193
1194 def peek(self, n=0):
1195 return self.reader.peek(n)
1196
1197 def read1(self, n):
1198 return self.reader.read1(n)
1199
1200 def readable(self):
1201 return self.reader.readable()
1202
1203 def writable(self):
1204 return self.writer.writable()
1205
1206 def flush(self):
1207 return self.writer.flush()
1208
1209 def close(self):
1210 self.writer.close()
1211 self.reader.close()
1212
1213 def isatty(self):
1214 return self.reader.isatty() or self.writer.isatty()
1215
1216 @property
1217 def closed(self):
1218 return self.writer.closed
1219
1220
1221class BufferedRandom(BufferedWriter, BufferedReader):
1222
1223 """A buffered interface to random access streams.
1224
1225 The constructor creates a reader and writer for a seekable stream,
1226 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001227 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001228 """
1229
Benjamin Peterson59406a92009-03-26 17:10:29 +00001230 _warning_stack_offset = 3
1231
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001232 def __init__(self, raw,
1233 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1234 raw._checkSeekable()
1235 BufferedReader.__init__(self, raw, buffer_size)
1236 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1237
1238 def seek(self, pos, whence=0):
1239 if not (0 <= whence <= 2):
1240 raise ValueError("invalid whence")
1241 self.flush()
1242 if self._read_buf:
1243 # Undo read ahead.
1244 with self._read_lock:
1245 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1246 # First do the raw seek, then empty the read buffer, so that
1247 # if the raw seek fails, we don't lose buffered data forever.
1248 pos = self.raw.seek(pos, whence)
1249 with self._read_lock:
1250 self._reset_read_buf()
1251 if pos < 0:
1252 raise IOError("seek() returned invalid position")
1253 return pos
1254
1255 def tell(self):
1256 if self._write_buf:
1257 return BufferedWriter.tell(self)
1258 else:
1259 return BufferedReader.tell(self)
1260
1261 def truncate(self, pos=None):
1262 if pos is None:
1263 pos = self.tell()
1264 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001265 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001266
1267 def read(self, n=None):
1268 if n is None:
1269 n = -1
1270 self.flush()
1271 return BufferedReader.read(self, n)
1272
1273 def readinto(self, b):
1274 self.flush()
1275 return BufferedReader.readinto(self, b)
1276
1277 def peek(self, n=0):
1278 self.flush()
1279 return BufferedReader.peek(self, n)
1280
1281 def read1(self, n):
1282 self.flush()
1283 return BufferedReader.read1(self, n)
1284
1285 def write(self, b):
1286 if self._read_buf:
1287 # Undo readahead
1288 with self._read_lock:
1289 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1290 self._reset_read_buf()
1291 return BufferedWriter.write(self, b)
1292
1293
1294class TextIOBase(IOBase):
1295
1296 """Base class for text I/O.
1297
1298 This class provides a character and line based interface to stream
1299 I/O. There is no readinto method because Python's character strings
1300 are immutable. There is no public constructor.
1301 """
1302
Georg Brandl4d73b572011-01-13 07:13:06 +00001303 def read(self, n=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001304 """Read at most n characters from stream, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001305
1306 Read from underlying buffer until we have n characters or we hit EOF.
1307 If n is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001308
1309 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001310 """
1311 self._unsupported("read")
1312
Raymond Hettinger3c940242011-01-12 23:39:31 +00001313 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001314 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001315 self._unsupported("write")
1316
Georg Brandl4d73b572011-01-13 07:13:06 +00001317 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001318 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001319 self._unsupported("truncate")
1320
Raymond Hettinger3c940242011-01-12 23:39:31 +00001321 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001322 """Read until newline or EOF.
1323
1324 Returns an empty string if EOF is hit immediately.
1325 """
1326 self._unsupported("readline")
1327
Raymond Hettinger3c940242011-01-12 23:39:31 +00001328 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001329 """
1330 Separate the underlying buffer from the TextIOBase and return it.
1331
1332 After the underlying buffer has been detached, the TextIO is in an
1333 unusable state.
1334 """
1335 self._unsupported("detach")
1336
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001337 @property
1338 def encoding(self):
1339 """Subclasses should override."""
1340 return None
1341
1342 @property
1343 def newlines(self):
1344 """Line endings translated so far.
1345
1346 Only line endings translated during reading are considered.
1347
1348 Subclasses should override.
1349 """
1350 return None
1351
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001352 @property
1353 def errors(self):
1354 """Error setting of the decoder or encoder.
1355
1356 Subclasses should override."""
1357 return None
1358
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001359io.TextIOBase.register(TextIOBase)
1360
1361
1362class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1363 r"""Codec used when reading a file in universal newlines mode. It wraps
1364 another incremental decoder, translating \r\n and \r into \n. It also
1365 records the types of newlines encountered. When used with
1366 translate=False, it ensures that the newline sequence is returned in
1367 one piece.
1368 """
1369 def __init__(self, decoder, translate, errors='strict'):
1370 codecs.IncrementalDecoder.__init__(self, errors=errors)
1371 self.translate = translate
1372 self.decoder = decoder
1373 self.seennl = 0
1374 self.pendingcr = False
1375
1376 def decode(self, input, final=False):
1377 # decode input (with the eventual \r from a previous pass)
1378 if self.decoder is None:
1379 output = input
1380 else:
1381 output = self.decoder.decode(input, final=final)
1382 if self.pendingcr and (output or final):
1383 output = "\r" + output
1384 self.pendingcr = False
1385
1386 # retain last \r even when not translating data:
1387 # then readline() is sure to get \r\n in one pass
1388 if output.endswith("\r") and not final:
1389 output = output[:-1]
1390 self.pendingcr = True
1391
1392 # Record which newlines are read
1393 crlf = output.count('\r\n')
1394 cr = output.count('\r') - crlf
1395 lf = output.count('\n') - crlf
1396 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1397 | (crlf and self._CRLF)
1398
1399 if self.translate:
1400 if crlf:
1401 output = output.replace("\r\n", "\n")
1402 if cr:
1403 output = output.replace("\r", "\n")
1404
1405 return output
1406
1407 def getstate(self):
1408 if self.decoder is None:
1409 buf = b""
1410 flag = 0
1411 else:
1412 buf, flag = self.decoder.getstate()
1413 flag <<= 1
1414 if self.pendingcr:
1415 flag |= 1
1416 return buf, flag
1417
1418 def setstate(self, state):
1419 buf, flag = state
1420 self.pendingcr = bool(flag & 1)
1421 if self.decoder is not None:
1422 self.decoder.setstate((buf, flag >> 1))
1423
1424 def reset(self):
1425 self.seennl = 0
1426 self.pendingcr = False
1427 if self.decoder is not None:
1428 self.decoder.reset()
1429
1430 _LF = 1
1431 _CR = 2
1432 _CRLF = 4
1433
1434 @property
1435 def newlines(self):
1436 return (None,
1437 "\n",
1438 "\r",
1439 ("\r", "\n"),
1440 "\r\n",
1441 ("\n", "\r\n"),
1442 ("\r", "\r\n"),
1443 ("\r", "\n", "\r\n")
1444 )[self.seennl]
1445
1446
1447class TextIOWrapper(TextIOBase):
1448
1449 r"""Character and line based layer over a BufferedIOBase object, buffer.
1450
1451 encoding gives the name of the encoding that the stream will be
1452 decoded or encoded with. It defaults to locale.getpreferredencoding.
1453
1454 errors determines the strictness of encoding and decoding (see the
1455 codecs.register) and defaults to "strict".
1456
1457 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1458 handling of line endings. If it is None, universal newlines is
1459 enabled. With this enabled, on input, the lines endings '\n', '\r',
1460 or '\r\n' are translated to '\n' before being returned to the
1461 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001462 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001463 legal values, that newline becomes the newline when the file is read
1464 and it is returned untranslated. On output, '\n' is converted to the
1465 newline.
1466
1467 If line_buffering is True, a call to flush is implied when a call to
1468 write contains a newline character.
1469 """
1470
1471 _CHUNK_SIZE = 2048
1472
1473 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001474 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001475 if newline is not None and not isinstance(newline, str):
1476 raise TypeError("illegal newline type: %r" % (type(newline),))
1477 if newline not in (None, "", "\n", "\r", "\r\n"):
1478 raise ValueError("illegal newline value: %r" % (newline,))
1479 if encoding is None:
1480 try:
1481 encoding = os.device_encoding(buffer.fileno())
1482 except (AttributeError, UnsupportedOperation):
1483 pass
1484 if encoding is None:
1485 try:
1486 import locale
1487 except ImportError:
1488 # Importing locale may fail if Python is being built
1489 encoding = "ascii"
1490 else:
1491 encoding = locale.getpreferredencoding()
1492
1493 if not isinstance(encoding, str):
1494 raise ValueError("invalid encoding: %r" % encoding)
1495
1496 if errors is None:
1497 errors = "strict"
1498 else:
1499 if not isinstance(errors, str):
1500 raise ValueError("invalid errors: %r" % errors)
1501
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001502 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001503 self._line_buffering = line_buffering
1504 self._encoding = encoding
1505 self._errors = errors
1506 self._readuniversal = not newline
1507 self._readtranslate = newline is None
1508 self._readnl = newline
1509 self._writetranslate = newline != ''
1510 self._writenl = newline or os.linesep
1511 self._encoder = None
1512 self._decoder = None
1513 self._decoded_chars = '' # buffer for text returned from decoder
1514 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1515 self._snapshot = None # info for reconstructing decoder state
1516 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001517 self._has_read1 = hasattr(self.buffer, 'read1')
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
1688 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
1689
1690 if self._telling:
1691 # At the snapshot point, len(dec_buffer) bytes before the read,
1692 # the next input to be decoded is dec_buffer + input_chunk.
1693 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1694
1695 return not eof
1696
1697 def _pack_cookie(self, position, dec_flags=0,
1698 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1699 # The meaning of a tell() cookie is: seek to position, set the
1700 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1701 # into the decoder with need_eof as the EOF flag, then skip
1702 # chars_to_skip characters of the decoded result. For most simple
1703 # decoders, tell() will often just give a byte offset in the file.
1704 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1705 (chars_to_skip<<192) | bool(need_eof)<<256)
1706
1707 def _unpack_cookie(self, bigint):
1708 rest, position = divmod(bigint, 1<<64)
1709 rest, dec_flags = divmod(rest, 1<<64)
1710 rest, bytes_to_feed = divmod(rest, 1<<64)
1711 need_eof, chars_to_skip = divmod(rest, 1<<64)
1712 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1713
1714 def tell(self):
1715 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001716 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001717 if not self._telling:
1718 raise IOError("telling position disabled by next() call")
1719 self.flush()
1720 position = self.buffer.tell()
1721 decoder = self._decoder
1722 if decoder is None or self._snapshot is None:
1723 if self._decoded_chars:
1724 # This should never happen.
1725 raise AssertionError("pending decoded text")
1726 return position
1727
1728 # Skip backward to the snapshot point (see _read_chunk).
1729 dec_flags, next_input = self._snapshot
1730 position -= len(next_input)
1731
1732 # How many decoded characters have been used up since the snapshot?
1733 chars_to_skip = self._decoded_chars_used
1734 if chars_to_skip == 0:
1735 # We haven't moved from the snapshot point.
1736 return self._pack_cookie(position, dec_flags)
1737
1738 # Starting from the snapshot position, we will walk the decoder
1739 # forward until it gives us enough decoded characters.
1740 saved_state = decoder.getstate()
1741 try:
1742 # Note our initial start point.
1743 decoder.setstate((b'', dec_flags))
1744 start_pos = position
1745 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1746 need_eof = 0
1747
1748 # Feed the decoder one byte at a time. As we go, note the
1749 # nearest "safe start point" before the current location
1750 # (a point where the decoder has nothing buffered, so seek()
1751 # can safely start from there and advance to this location).
1752 next_byte = bytearray(1)
1753 for next_byte[0] in next_input:
1754 bytes_fed += 1
1755 chars_decoded += len(decoder.decode(next_byte))
1756 dec_buffer, dec_flags = decoder.getstate()
1757 if not dec_buffer and chars_decoded <= chars_to_skip:
1758 # Decoder buffer is empty, so this is a safe start point.
1759 start_pos += bytes_fed
1760 chars_to_skip -= chars_decoded
1761 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1762 if chars_decoded >= chars_to_skip:
1763 break
1764 else:
1765 # We didn't get enough decoded data; signal EOF to get more.
1766 chars_decoded += len(decoder.decode(b'', final=True))
1767 need_eof = 1
1768 if chars_decoded < chars_to_skip:
1769 raise IOError("can't reconstruct logical file position")
1770
1771 # The returned cookie corresponds to the last safe start point.
1772 return self._pack_cookie(
1773 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1774 finally:
1775 decoder.setstate(saved_state)
1776
1777 def truncate(self, pos=None):
1778 self.flush()
1779 if pos is None:
1780 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001781 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001782
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001783 def detach(self):
1784 if self.buffer is None:
1785 raise ValueError("buffer is already detached")
1786 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001787 buffer = self._buffer
1788 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001789 return buffer
1790
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001791 def seek(self, cookie, whence=0):
1792 if self.closed:
1793 raise ValueError("tell on closed file")
1794 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001795 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001796 if whence == 1: # seek relative to current position
1797 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001798 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001799 # Seeking to the current position should attempt to
1800 # sync the underlying buffer with the current position.
1801 whence = 0
1802 cookie = self.tell()
1803 if whence == 2: # seek relative to end of file
1804 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001805 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001806 self.flush()
1807 position = self.buffer.seek(0, 2)
1808 self._set_decoded_chars('')
1809 self._snapshot = None
1810 if self._decoder:
1811 self._decoder.reset()
1812 return position
1813 if whence != 0:
1814 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
1815 (whence,))
1816 if cookie < 0:
1817 raise ValueError("negative seek position %r" % (cookie,))
1818 self.flush()
1819
1820 # The strategy of seek() is to go back to the safe start point
1821 # and replay the effect of read(chars_to_skip) from there.
1822 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1823 self._unpack_cookie(cookie)
1824
1825 # Seek back to the safe start point.
1826 self.buffer.seek(start_pos)
1827 self._set_decoded_chars('')
1828 self._snapshot = None
1829
1830 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001831 if cookie == 0 and self._decoder:
1832 self._decoder.reset()
1833 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001834 self._decoder = self._decoder or self._get_decoder()
1835 self._decoder.setstate((b'', dec_flags))
1836 self._snapshot = (dec_flags, b'')
1837
1838 if chars_to_skip:
1839 # Just like _read_chunk, feed the decoder and save a snapshot.
1840 input_chunk = self.buffer.read(bytes_to_feed)
1841 self._set_decoded_chars(
1842 self._decoder.decode(input_chunk, need_eof))
1843 self._snapshot = (dec_flags, input_chunk)
1844
1845 # Skip chars_to_skip of the decoded characters.
1846 if len(self._decoded_chars) < chars_to_skip:
1847 raise IOError("can't restore logical file position")
1848 self._decoded_chars_used = chars_to_skip
1849
Antoine Pitroue4501852009-05-14 18:55:55 +00001850 # Finally, reset the encoder (merely useful for proper BOM handling)
1851 try:
1852 encoder = self._encoder or self._get_encoder()
1853 except LookupError:
1854 # Sometimes the encoder doesn't exist
1855 pass
1856 else:
1857 if cookie != 0:
1858 encoder.setstate(0)
1859 else:
1860 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001861 return cookie
1862
1863 def read(self, n=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00001864 self._checkReadable()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001865 if n is None:
1866 n = -1
1867 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00001868 try:
1869 n.__index__
1870 except AttributeError as err:
1871 raise TypeError("an integer is required") from err
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001872 if n < 0:
1873 # Read everything.
1874 result = (self._get_decoded_chars() +
1875 decoder.decode(self.buffer.read(), final=True))
1876 self._set_decoded_chars('')
1877 self._snapshot = None
1878 return result
1879 else:
1880 # Keep reading chunks until we have n characters to return.
1881 eof = False
1882 result = self._get_decoded_chars(n)
1883 while len(result) < n and not eof:
1884 eof = not self._read_chunk()
1885 result += self._get_decoded_chars(n - len(result))
1886 return result
1887
1888 def __next__(self):
1889 self._telling = False
1890 line = self.readline()
1891 if not line:
1892 self._snapshot = None
1893 self._telling = self._seekable
1894 raise StopIteration
1895 return line
1896
1897 def readline(self, limit=None):
1898 if self.closed:
1899 raise ValueError("read from closed file")
1900 if limit is None:
1901 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +00001902 elif not isinstance(limit, int):
1903 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001904
1905 # Grab all the decoded text (we will rewind any extra bits later).
1906 line = self._get_decoded_chars()
1907
1908 start = 0
1909 # Make the decoder if it doesn't already exist.
1910 if not self._decoder:
1911 self._get_decoder()
1912
1913 pos = endpos = None
1914 while True:
1915 if self._readtranslate:
1916 # Newlines are already translated, only search for \n
1917 pos = line.find('\n', start)
1918 if pos >= 0:
1919 endpos = pos + 1
1920 break
1921 else:
1922 start = len(line)
1923
1924 elif self._readuniversal:
1925 # Universal newline search. Find any of \r, \r\n, \n
1926 # The decoder ensures that \r\n are not split in two pieces
1927
1928 # In C we'd look for these in parallel of course.
1929 nlpos = line.find("\n", start)
1930 crpos = line.find("\r", start)
1931 if crpos == -1:
1932 if nlpos == -1:
1933 # Nothing found
1934 start = len(line)
1935 else:
1936 # Found \n
1937 endpos = nlpos + 1
1938 break
1939 elif nlpos == -1:
1940 # Found lone \r
1941 endpos = crpos + 1
1942 break
1943 elif nlpos < crpos:
1944 # Found \n
1945 endpos = nlpos + 1
1946 break
1947 elif nlpos == crpos + 1:
1948 # Found \r\n
1949 endpos = crpos + 2
1950 break
1951 else:
1952 # Found \r
1953 endpos = crpos + 1
1954 break
1955 else:
1956 # non-universal
1957 pos = line.find(self._readnl)
1958 if pos >= 0:
1959 endpos = pos + len(self._readnl)
1960 break
1961
1962 if limit >= 0 and len(line) >= limit:
1963 endpos = limit # reached length limit
1964 break
1965
1966 # No line ending seen yet - get more data'
1967 while self._read_chunk():
1968 if self._decoded_chars:
1969 break
1970 if self._decoded_chars:
1971 line += self._get_decoded_chars()
1972 else:
1973 # end of file
1974 self._set_decoded_chars('')
1975 self._snapshot = None
1976 return line
1977
1978 if limit >= 0 and endpos > limit:
1979 endpos = limit # don't exceed limit
1980
1981 # Rewind _decoded_chars to just after the line ending we found.
1982 self._rewind_decoded_chars(len(line) - endpos)
1983 return line[:endpos]
1984
1985 @property
1986 def newlines(self):
1987 return self._decoder.newlines if self._decoder else None
1988
1989
1990class StringIO(TextIOWrapper):
1991 """Text I/O implementation using an in-memory buffer.
1992
1993 The initial_value argument sets the value of object. The newline
1994 argument is like the one of TextIOWrapper's constructor.
1995 """
1996
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001997 def __init__(self, initial_value="", newline="\n"):
1998 super(StringIO, self).__init__(BytesIO(),
1999 encoding="utf-8",
2000 errors="strict",
2001 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002002 # Issue #5645: make universal newlines semantics the same as in the
2003 # C version, even under Windows.
2004 if newline is None:
2005 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002006 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002007 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002008 raise TypeError("initial_value must be str or None, not {0}"
2009 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002010 initial_value = str(initial_value)
2011 self.write(initial_value)
2012 self.seek(0)
2013
2014 def getvalue(self):
2015 self.flush()
2016 return self.buffer.getvalue().decode(self._encoding, self._errors)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002017
2018 def __repr__(self):
2019 # TextIOWrapper tells the encoding in its repr. In StringIO,
2020 # that's a implementation detail.
2021 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002022
2023 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002024 def errors(self):
2025 return None
2026
2027 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002028 def encoding(self):
2029 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002030
2031 def detach(self):
2032 # This doesn't make sense on StringIO.
2033 self._unsupported("detach")