blob: a9ff985527ad51fdb9a541680789a4fa8cb5ca93 [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
16from io import __all__
Benjamin Peterson8d5fd4e2009-04-02 01:03:26 +000017from io import SEEK_SET, SEEK_CUR, SEEK_END
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000018
19# open() uses st_blksize whenever we can
20DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
21
22# NOTE: Base classes defined here are registered with the "official" ABCs
23# defined in io.py. We don't use real inheritance though, because we don't
24# want to inherit the C implementations.
25
26
27class BlockingIOError(IOError):
28
29 """Exception raised when I/O would block on a non-blocking I/O stream."""
30
31 def __init__(self, errno, strerror, characters_written=0):
32 super().__init__(errno, strerror)
33 if not isinstance(characters_written, int):
34 raise TypeError("characters_written must be a integer")
35 self.characters_written = characters_written
36
37
Benjamin Peterson9990e8c2009-04-18 14:47:50 +000038def open(file: (str, bytes), mode: str = "r", buffering: int = None,
39 encoding: str = None, errors: str = None,
40 newline: str = None, closefd: bool = True) -> "IOBase":
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 Pitrou45a43722009-12-19 21:09:58 +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
100 encoding is the name of the encoding used to decode or encode the
101 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
113 newline controls how universal newlines works (it only applies to text
114 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
115 follows:
116
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
131 If closefd is False, the underlying file descriptor will be kept open
132 when the file is closed. This does not work when a file name is given
133 and must be True in that case.
134
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)
153 if buffering is not None and not isinstance(buffering, int):
154 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)
190 if buffering is None:
191 buffering = -1
192 line_buffering = False
193 if buffering == 1 or buffering < 0 and raw.isatty():
194 buffering = -1
195 line_buffering = True
196 if buffering < 0:
197 buffering = DEFAULT_BUFFER_SIZE
198 try:
199 bs = os.fstat(raw.fileno()).st_blksize
200 except (os.error, AttributeError):
201 pass
202 else:
203 if bs > 1:
204 buffering = bs
205 if buffering < 0:
206 raise ValueError("invalid buffering size")
207 if buffering == 0:
208 if binary:
209 return raw
210 raise ValueError("can't have unbuffered text I/O")
211 if updating:
212 buffer = BufferedRandom(raw, buffering)
213 elif writing or appending:
214 buffer = BufferedWriter(raw, buffering)
215 elif reading:
216 buffer = BufferedReader(raw, buffering)
217 else:
218 raise ValueError("unknown mode: %r" % mode)
219 if binary:
220 return buffer
221 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
222 text.mode = mode
223 return text
224
225
226class DocDescriptor:
227 """Helper for builtins.open.__doc__
228 """
229 def __get__(self, obj, typ):
230 return (
231 "open(file, mode='r', buffering=None, encoding=None, "
232 "errors=None, newline=None, closefd=True)\n\n" +
233 open.__doc__)
234
235class OpenWrapper:
236 """Wrapper for builtins.open
237
238 Trick so that open won't become a bound method when stored
239 as a class variable (as dbm.dumb does).
240
241 See initstdio() in Python/pythonrun.c.
242 """
243 __doc__ = DocDescriptor()
244
245 def __new__(cls, *args, **kwargs):
246 return open(*args, **kwargs)
247
248
249class UnsupportedOperation(ValueError, IOError):
250 pass
251
252
253class IOBase(metaclass=abc.ABCMeta):
254
255 """The abstract base class for all I/O classes, acting on streams of
256 bytes. There is no public constructor.
257
258 This class provides dummy implementations for many methods that
259 derived classes can override selectively; the default implementations
260 represent a file that cannot be read, written or seeked.
261
262 Even though IOBase does not declare read, readinto, or write because
263 their signatures will vary, implementations and clients should
264 consider those methods part of the interface. Also, implementations
265 may raise a IOError when operations they do not support are called.
266
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
287 def _unsupported(self, name: str) -> IOError:
288 """Internal: raise an exception for unsupported operations."""
289 raise UnsupportedOperation("%s.%s() not supported" %
290 (self.__class__.__name__, name))
291
292 ### Positioning ###
293
294 def seek(self, pos: int, whence: int = 0) -> int:
295 """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
299 for whence are:
300
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
305 Return the new absolute position.
306 """
307 self._unsupported("seek")
308
309 def tell(self) -> int:
310 """Return current stream position."""
311 return self.seek(0, 1)
312
313 def truncate(self, pos: int = None) -> int:
314 """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
323 def flush(self) -> None:
324 """Flush write buffers, if applicable.
325
326 This is not implemented for read-only and non-blocking streams.
327 """
328 # XXX Should this return the number of bytes written???
329
330 __closed = False
331
332 def close(self) -> None:
333 """Flush and close the IO object.
334
335 This method has no effect if the file is already closed.
336 """
337 if not self.__closed:
338 try:
339 self.flush()
340 except IOError:
341 pass # If flush() fails, just give up
342 self.__closed = True
343
344 def __del__(self) -> None:
345 """Destructor. Calls close()."""
346 # The try/except block is in case this is called at program
347 # exit time, when it's possible that globals have already been
348 # deleted, and then the close() call might fail. Since
349 # there's nothing we can do about such failures and they annoy
350 # the end users, we suppress the traceback.
351 try:
352 self.close()
353 except:
354 pass
355
356 ### Inquiries ###
357
358 def seekable(self) -> bool:
359 """Return whether object supports random access.
360
361 If False, seek(), tell() and truncate() will raise IOError.
362 This method may need to do a test seek().
363 """
364 return False
365
366 def _checkSeekable(self, msg=None):
367 """Internal: raise an IOError if file is not seekable
368 """
369 if not self.seekable():
370 raise IOError("File or stream is not seekable."
371 if msg is None else msg)
372
373
374 def readable(self) -> bool:
375 """Return whether object was opened for reading.
376
377 If False, read() will raise IOError.
378 """
379 return False
380
381 def _checkReadable(self, msg=None):
382 """Internal: raise an IOError if file is not readable
383 """
384 if not self.readable():
385 raise IOError("File or stream is not readable."
386 if msg is None else msg)
387
388 def writable(self) -> bool:
389 """Return whether object was opened for writing.
390
391 If False, write() and truncate() will raise IOError.
392 """
393 return False
394
395 def _checkWritable(self, msg=None):
396 """Internal: raise an IOError if file is not writable
397 """
398 if not self.writable():
399 raise IOError("File or stream is not writable."
400 if msg is None else msg)
401
402 @property
403 def closed(self):
404 """closed: bool. True iff the file has been closed.
405
406 For backwards compatibility, this is a property, not a predicate.
407 """
408 return self.__closed
409
410 def _checkClosed(self, msg=None):
411 """Internal: raise an ValueError if file is closed
412 """
413 if self.closed:
414 raise ValueError("I/O operation on closed file."
415 if msg is None else msg)
416
417 ### Context manager ###
418
419 def __enter__(self) -> "IOBase": # That's a forward reference
420 """Context management protocol. Returns self."""
421 self._checkClosed()
422 return self
423
424 def __exit__(self, *args) -> None:
425 """Context management protocol. Calls close()"""
426 self.close()
427
428 ### Lower-level APIs ###
429
430 # XXX Should these be present even if unimplemented?
431
432 def fileno(self) -> int:
433 """Returns underlying file descriptor if one exists.
434
435 An IOError is raised if the IO object does not use a file descriptor.
436 """
437 self._unsupported("fileno")
438
439 def isatty(self) -> bool:
440 """Return whether this is an 'interactive' stream.
441
442 Return False if it can't be determined.
443 """
444 self._checkClosed()
445 return False
446
447 ### Readline[s] and writelines ###
448
449 def readline(self, limit: int = -1) -> bytes:
450 r"""Read and return a line from the stream.
451
452 If limit is specified, at most limit bytes will be read.
453
454 The line terminator is always b'\n' for binary files; for text
455 files, the newlines argument to open can be used to select the line
456 terminator(s) recognized.
457 """
458 # For backwards compatibility, a (slowish) readline().
459 if hasattr(self, "peek"):
460 def nreadahead():
461 readahead = self.peek(1)
462 if not readahead:
463 return 1
464 n = (readahead.find(b"\n") + 1) or len(readahead)
465 if limit >= 0:
466 n = min(n, limit)
467 return n
468 else:
469 def nreadahead():
470 return 1
471 if limit is None:
472 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +0000473 elif not isinstance(limit, int):
474 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000475 res = bytearray()
476 while limit < 0 or len(res) < limit:
477 b = self.read(nreadahead())
478 if not b:
479 break
480 res += b
481 if res.endswith(b"\n"):
482 break
483 return bytes(res)
484
485 def __iter__(self):
486 self._checkClosed()
487 return self
488
489 def __next__(self):
490 line = self.readline()
491 if not line:
492 raise StopIteration
493 return line
494
495 def readlines(self, hint=None):
496 """Return a list of lines from the stream.
497
498 hint can be specified to control the number of lines read: no more
499 lines will be read if the total size (in bytes/characters) of all
500 lines so far exceeds hint.
501 """
502 if hint is None or hint <= 0:
503 return list(self)
504 n = 0
505 lines = []
506 for line in self:
507 lines.append(line)
508 n += len(line)
509 if n >= hint:
510 break
511 return lines
512
513 def writelines(self, lines):
514 self._checkClosed()
515 for line in lines:
516 self.write(line)
517
518io.IOBase.register(IOBase)
519
520
521class RawIOBase(IOBase):
522
523 """Base class for raw binary I/O."""
524
525 # The read() method is implemented by calling readinto(); derived
526 # classes that want to support read() only need to implement
527 # readinto() as a primitive operation. In general, readinto() can be
528 # more efficient than read().
529
530 # (It would be tempting to also provide an implementation of
531 # readinto() in terms of read(), in case the latter is a more suitable
532 # primitive operation, but that would lead to nasty recursion in case
533 # a subclass doesn't implement either.)
534
535 def read(self, n: int = -1) -> bytes:
536 """Read and return up to n bytes.
537
538 Returns an empty bytes object on EOF, or None if the object is
539 set not to block and has no data to read.
540 """
541 if n is None:
542 n = -1
543 if n < 0:
544 return self.readall()
545 b = bytearray(n.__index__())
546 n = self.readinto(b)
547 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
558 return bytes(res)
559
560 def readinto(self, b: bytearray) -> int:
561 """Read up to len(b) bytes into b.
562
563 Returns number of bytes read (0 for EOF), or None if the object
564 is set not to block as has no data to read.
565 """
566 self._unsupported("readinto")
567
568 def write(self, b: bytes) -> int:
569 """Write the given buffer to the IO stream.
570
571 Returns the number of bytes written, which may be less than len(b).
572 """
573 self._unsupported("write")
574
575io.RawIOBase.register(RawIOBase)
576from _io import FileIO
577RawIOBase.register(FileIO)
578
579
580class BufferedIOBase(IOBase):
581
582 """Base class for buffered IO objects.
583
584 The main difference with RawIOBase is that the read() method
585 supports omitting the size argument, and does not have a default
586 implementation that defers to readinto().
587
588 In addition, read(), readinto() and write() may raise
589 BlockingIOError if the underlying raw stream is in non-blocking
590 mode and not ready; unlike their raw counterparts, they will never
591 return None.
592
593 A typical implementation should not inherit from a RawIOBase
594 implementation, but wrap one.
595 """
596
597 def read(self, n: int = None) -> bytes:
598 """Read and return up to n bytes.
599
600 If the argument is omitted, None, or negative, reads and
601 returns all data until EOF.
602
603 If the argument is positive, and the underlying raw stream is
604 not 'interactive', multiple raw reads may be issued to satisfy
605 the byte count (unless EOF is reached first). But for
606 interactive raw streams (XXX and for pipes?), at most one raw
607 read will be issued, and a short result does not imply that
608 EOF is imminent.
609
610 Returns an empty bytes array on EOF.
611
612 Raises BlockingIOError if the underlying raw stream has no
613 data at the moment.
614 """
615 self._unsupported("read")
616
617 def read1(self, n: int=None) -> bytes:
618 """Read up to n bytes with at most one read() system call."""
619 self._unsupported("read1")
620
621 def readinto(self, b: bytearray) -> int:
622 """Read up to len(b) bytes into b.
623
624 Like read(), this may issue multiple reads to the underlying raw
625 stream, unless the latter is 'interactive'.
626
627 Returns the number of bytes read (0 for EOF).
628
629 Raises BlockingIOError if the underlying raw stream has no
630 data at the moment.
631 """
632 # XXX This ought to work with anything that supports the buffer API
633 data = self.read(len(b))
634 n = len(data)
635 try:
636 b[:n] = data
637 except TypeError as err:
638 import array
639 if not isinstance(b, array.array):
640 raise err
641 b[:n] = array.array('b', data)
642 return n
643
644 def write(self, b: bytes) -> int:
645 """Write the given buffer to the IO stream.
646
647 Return the number of bytes written, which is never less than
648 len(b).
649
650 Raises BlockingIOError if the buffer is full and the
651 underlying raw stream cannot accept more data at the moment.
652 """
653 self._unsupported("write")
654
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000655 def detach(self) -> None:
656 """
657 Separate the underlying raw stream from the buffer and return it.
658
659 After the raw stream has been detached, the buffer is in an unusable
660 state.
661 """
662 self._unsupported("detach")
663
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000664io.BufferedIOBase.register(BufferedIOBase)
665
666
667class _BufferedIOMixin(BufferedIOBase):
668
669 """A mixin implementation of BufferedIOBase with an underlying raw stream.
670
671 This passes most requests on to the underlying raw stream. It
672 does *not* provide implementations of read(), readinto() or
673 write().
674 """
675
676 def __init__(self, raw):
677 self.raw = raw
678
679 ### Positioning ###
680
681 def seek(self, pos, whence=0):
682 new_position = self.raw.seek(pos, whence)
683 if new_position < 0:
684 raise IOError("seek() returned an invalid position")
685 return new_position
686
687 def tell(self):
688 pos = self.raw.tell()
689 if pos < 0:
690 raise IOError("tell() returned an invalid position")
691 return pos
692
693 def truncate(self, pos=None):
694 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
695 # and a flush may be necessary to synch both views of the current
696 # file state.
697 self.flush()
698
699 if pos is None:
700 pos = self.tell()
701 # XXX: Should seek() be used, instead of passing the position
702 # XXX directly to truncate?
703 return self.raw.truncate(pos)
704
705 ### Flush and close ###
706
707 def flush(self):
708 self.raw.flush()
709
710 def close(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000711 if not self.closed and self.raw is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000712 try:
713 self.flush()
714 except IOError:
715 pass # If flush() fails, just give up
716 self.raw.close()
717
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000718 def detach(self):
719 if self.raw is None:
720 raise ValueError("raw stream already detached")
721 self.flush()
722 raw = self.raw
723 self.raw = None
724 return raw
725
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000726 ### Inquiries ###
727
728 def seekable(self):
729 return self.raw.seekable()
730
731 def readable(self):
732 return self.raw.readable()
733
734 def writable(self):
735 return self.raw.writable()
736
737 @property
738 def closed(self):
739 return self.raw.closed
740
741 @property
742 def name(self):
743 return self.raw.name
744
745 @property
746 def mode(self):
747 return self.raw.mode
748
Antoine Pitrou716c4442009-05-23 19:04:03 +0000749 def __repr__(self):
750 clsname = self.__class__.__name__
751 try:
752 name = self.name
753 except AttributeError:
754 return "<_pyio.{0}>".format(clsname)
755 else:
756 return "<_pyio.{0} name={1!r}>".format(clsname, name)
757
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000758 ### Lower-level APIs ###
759
760 def fileno(self):
761 return self.raw.fileno()
762
763 def isatty(self):
764 return self.raw.isatty()
765
766
767class BytesIO(BufferedIOBase):
768
769 """Buffered I/O implementation using an in-memory bytes buffer."""
770
771 def __init__(self, initial_bytes=None):
772 buf = bytearray()
773 if initial_bytes is not None:
774 buf += initial_bytes
775 self._buffer = buf
776 self._pos = 0
777
778 def getvalue(self):
779 """Return the bytes value (contents) of the buffer
780 """
781 if self.closed:
782 raise ValueError("getvalue on closed file")
783 return bytes(self._buffer)
784
785 def read(self, n=None):
786 if self.closed:
787 raise ValueError("read from closed file")
788 if n is None:
789 n = -1
790 if n < 0:
791 n = len(self._buffer)
792 if len(self._buffer) <= self._pos:
793 return b""
794 newpos = min(len(self._buffer), self._pos + n)
795 b = self._buffer[self._pos : newpos]
796 self._pos = newpos
797 return bytes(b)
798
799 def read1(self, n):
800 """This is the same as read.
801 """
802 return self.read(n)
803
804 def write(self, b):
805 if self.closed:
806 raise ValueError("write to closed file")
807 if isinstance(b, str):
808 raise TypeError("can't write str to binary stream")
809 n = len(b)
810 if n == 0:
811 return 0
812 pos = self._pos
813 if pos > len(self._buffer):
814 # Inserts null bytes between the current end of the file
815 # and the new write position.
816 padding = b'\x00' * (pos - len(self._buffer))
817 self._buffer += padding
818 self._buffer[pos:pos + n] = b
819 self._pos += n
820 return n
821
822 def seek(self, pos, whence=0):
823 if self.closed:
824 raise ValueError("seek on closed file")
825 try:
826 pos = pos.__index__()
827 except AttributeError as err:
828 raise TypeError("an integer is required") from err
829 if whence == 0:
830 if pos < 0:
831 raise ValueError("negative seek position %r" % (pos,))
832 self._pos = pos
833 elif whence == 1:
834 self._pos = max(0, self._pos + pos)
835 elif whence == 2:
836 self._pos = max(0, len(self._buffer) + pos)
837 else:
838 raise ValueError("invalid whence value")
839 return self._pos
840
841 def tell(self):
842 if self.closed:
843 raise ValueError("tell on closed file")
844 return self._pos
845
846 def truncate(self, pos=None):
847 if self.closed:
848 raise ValueError("truncate on closed file")
849 if pos is None:
850 pos = self._pos
851 elif pos < 0:
852 raise ValueError("negative truncate position %r" % (pos,))
853 del self._buffer[pos:]
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000854 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000855
856 def readable(self):
857 return True
858
859 def writable(self):
860 return True
861
862 def seekable(self):
863 return True
864
865
866class BufferedReader(_BufferedIOMixin):
867
868 """BufferedReader(raw[, buffer_size])
869
870 A buffer for a readable, sequential BaseRawIO object.
871
872 The constructor creates a BufferedReader for the given readable raw
873 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
874 is used.
875 """
876
877 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
878 """Create a new buffered reader using the given readable raw IO object.
879 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000880 if not raw.readable():
881 raise IOError('"raw" argument must be readable.')
882
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000883 _BufferedIOMixin.__init__(self, raw)
884 if buffer_size <= 0:
885 raise ValueError("invalid buffer size")
886 self.buffer_size = buffer_size
887 self._reset_read_buf()
888 self._read_lock = Lock()
889
890 def _reset_read_buf(self):
891 self._read_buf = b""
892 self._read_pos = 0
893
894 def read(self, n=None):
895 """Read n bytes.
896
897 Returns exactly n bytes of data unless the underlying raw IO
898 stream reaches EOF or if the call would block in non-blocking
899 mode. If n is negative, read until EOF or until read() would
900 block.
901 """
902 if n is not None and n < -1:
903 raise ValueError("invalid number of bytes to read")
904 with self._read_lock:
905 return self._read_unlocked(n)
906
907 def _read_unlocked(self, n=None):
908 nodata_val = b""
909 empty_values = (b"", None)
910 buf = self._read_buf
911 pos = self._read_pos
912
913 # Special case for when the number of bytes to read is unspecified.
914 if n is None or n == -1:
915 self._reset_read_buf()
916 chunks = [buf[pos:]] # Strip the consumed bytes.
917 current_size = 0
918 while True:
919 # Read until EOF or until read() would block.
920 chunk = self.raw.read()
921 if chunk in empty_values:
922 nodata_val = chunk
923 break
924 current_size += len(chunk)
925 chunks.append(chunk)
926 return b"".join(chunks) or nodata_val
927
928 # The number of bytes to read is specified, return at most n bytes.
929 avail = len(buf) - pos # Length of the available buffered data.
930 if n <= avail:
931 # Fast path: the data to read is fully buffered.
932 self._read_pos += n
933 return buf[pos:pos+n]
934 # Slow path: read from the stream until enough bytes are read,
935 # or until an EOF occurs or until read() would block.
936 chunks = [buf[pos:]]
937 wanted = max(self.buffer_size, n)
938 while avail < n:
939 chunk = self.raw.read(wanted)
940 if chunk in empty_values:
941 nodata_val = chunk
942 break
943 avail += len(chunk)
944 chunks.append(chunk)
945 # n is more then avail only when an EOF occurred or when
946 # read() would have blocked.
947 n = min(n, avail)
948 out = b"".join(chunks)
949 self._read_buf = out[n:] # Save the extra data in the buffer.
950 self._read_pos = 0
951 return out[:n] if out else nodata_val
952
953 def peek(self, n=0):
954 """Returns buffered bytes without advancing the position.
955
956 The argument indicates a desired minimal number of bytes; we
957 do at most one raw read to satisfy it. We never return more
958 than self.buffer_size.
959 """
960 with self._read_lock:
961 return self._peek_unlocked(n)
962
963 def _peek_unlocked(self, n=0):
964 want = min(n, self.buffer_size)
965 have = len(self._read_buf) - self._read_pos
966 if have < want or have <= 0:
967 to_read = self.buffer_size - have
968 current = self.raw.read(to_read)
969 if current:
970 self._read_buf = self._read_buf[self._read_pos:] + current
971 self._read_pos = 0
972 return self._read_buf[self._read_pos:]
973
974 def read1(self, n):
975 """Reads up to n bytes, with at most one read() system call."""
976 # Returns up to n bytes. If at least one byte is buffered, we
977 # only return buffered bytes. Otherwise, we do one raw read.
978 if n < 0:
979 raise ValueError("number of bytes to read must be positive")
980 if n == 0:
981 return b""
982 with self._read_lock:
983 self._peek_unlocked(1)
984 return self._read_unlocked(
985 min(n, len(self._read_buf) - self._read_pos))
986
987 def tell(self):
988 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
989
990 def seek(self, pos, whence=0):
991 if not (0 <= whence <= 2):
992 raise ValueError("invalid whence value")
993 with self._read_lock:
994 if whence == 1:
995 pos -= len(self._read_buf) - self._read_pos
996 pos = _BufferedIOMixin.seek(self, pos, whence)
997 self._reset_read_buf()
998 return pos
999
1000class BufferedWriter(_BufferedIOMixin):
1001
1002 """A buffer for a writeable sequential RawIO object.
1003
1004 The constructor creates a BufferedWriter for the given writeable raw
1005 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001006 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001007 """
1008
Benjamin Peterson59406a92009-03-26 17:10:29 +00001009 _warning_stack_offset = 2
1010
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001011 def __init__(self, raw,
1012 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001013 if not raw.writable():
1014 raise IOError('"raw" argument must be writable.')
1015
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001016 _BufferedIOMixin.__init__(self, raw)
1017 if buffer_size <= 0:
1018 raise ValueError("invalid buffer size")
Benjamin Peterson59406a92009-03-26 17:10:29 +00001019 if max_buffer_size is not None:
1020 warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
1021 self._warning_stack_offset)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001022 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001023 self._write_buf = bytearray()
1024 self._write_lock = Lock()
1025
1026 def write(self, b):
1027 if self.closed:
1028 raise ValueError("write to closed file")
1029 if isinstance(b, str):
1030 raise TypeError("can't write str to binary stream")
1031 with self._write_lock:
1032 # XXX we can implement some more tricks to try and avoid
1033 # partial writes
1034 if len(self._write_buf) > self.buffer_size:
1035 # We're full, so let's pre-flush the buffer
1036 try:
1037 self._flush_unlocked()
1038 except BlockingIOError as e:
1039 # We can't accept anything else.
1040 # XXX Why not just let the exception pass through?
1041 raise BlockingIOError(e.errno, e.strerror, 0)
1042 before = len(self._write_buf)
1043 self._write_buf.extend(b)
1044 written = len(self._write_buf) - before
1045 if len(self._write_buf) > self.buffer_size:
1046 try:
1047 self._flush_unlocked()
1048 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001049 if len(self._write_buf) > self.buffer_size:
1050 # We've hit the buffer_size. We have to accept a partial
1051 # write and cut back our buffer.
1052 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001053 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001054 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001055 raise BlockingIOError(e.errno, e.strerror, written)
1056 return written
1057
1058 def truncate(self, pos=None):
1059 with self._write_lock:
1060 self._flush_unlocked()
1061 if pos is None:
1062 pos = self.raw.tell()
1063 return self.raw.truncate(pos)
1064
1065 def flush(self):
1066 with self._write_lock:
1067 self._flush_unlocked()
1068
1069 def _flush_unlocked(self):
1070 if self.closed:
1071 raise ValueError("flush of closed file")
1072 written = 0
1073 try:
1074 while self._write_buf:
1075 n = self.raw.write(self._write_buf)
1076 if n > len(self._write_buf) or n < 0:
1077 raise IOError("write() returned incorrect number of bytes")
1078 del self._write_buf[:n]
1079 written += n
1080 except BlockingIOError as e:
1081 n = e.characters_written
1082 del self._write_buf[:n]
1083 written += n
1084 raise BlockingIOError(e.errno, e.strerror, written)
1085
1086 def tell(self):
1087 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1088
1089 def seek(self, pos, whence=0):
1090 if not (0 <= whence <= 2):
1091 raise ValueError("invalid whence")
1092 with self._write_lock:
1093 self._flush_unlocked()
1094 return _BufferedIOMixin.seek(self, pos, whence)
1095
1096
1097class BufferedRWPair(BufferedIOBase):
1098
1099 """A buffered reader and writer object together.
1100
1101 A buffered reader object and buffered writer object put together to
1102 form a sequential IO object that can read and write. This is typically
1103 used with a socket or two-way pipe.
1104
1105 reader and writer are RawIOBase objects that are readable and
1106 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001107 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001108 """
1109
1110 # XXX The usefulness of this (compared to having two separate IO
1111 # objects) is questionable.
1112
1113 def __init__(self, reader, writer,
1114 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1115 """Constructor.
1116
1117 The arguments are two RawIO instances.
1118 """
Benjamin Peterson59406a92009-03-26 17:10:29 +00001119 if max_buffer_size is not None:
1120 warnings.warn("max_buffer_size is deprecated", DeprecationWarning, 2)
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001121
1122 if not reader.readable():
1123 raise IOError('"reader" argument must be readable.')
1124
1125 if not writer.writable():
1126 raise IOError('"writer" argument must be writable.')
1127
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001128 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001129 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001130
1131 def read(self, n=None):
1132 if n is None:
1133 n = -1
1134 return self.reader.read(n)
1135
1136 def readinto(self, b):
1137 return self.reader.readinto(b)
1138
1139 def write(self, b):
1140 return self.writer.write(b)
1141
1142 def peek(self, n=0):
1143 return self.reader.peek(n)
1144
1145 def read1(self, n):
1146 return self.reader.read1(n)
1147
1148 def readable(self):
1149 return self.reader.readable()
1150
1151 def writable(self):
1152 return self.writer.writable()
1153
1154 def flush(self):
1155 return self.writer.flush()
1156
1157 def close(self):
1158 self.writer.close()
1159 self.reader.close()
1160
1161 def isatty(self):
1162 return self.reader.isatty() or self.writer.isatty()
1163
1164 @property
1165 def closed(self):
1166 return self.writer.closed
1167
1168
1169class BufferedRandom(BufferedWriter, BufferedReader):
1170
1171 """A buffered interface to random access streams.
1172
1173 The constructor creates a reader and writer for a seekable stream,
1174 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001175 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001176 """
1177
Benjamin Peterson59406a92009-03-26 17:10:29 +00001178 _warning_stack_offset = 3
1179
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001180 def __init__(self, raw,
1181 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1182 raw._checkSeekable()
1183 BufferedReader.__init__(self, raw, buffer_size)
1184 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1185
1186 def seek(self, pos, whence=0):
1187 if not (0 <= whence <= 2):
1188 raise ValueError("invalid whence")
1189 self.flush()
1190 if self._read_buf:
1191 # Undo read ahead.
1192 with self._read_lock:
1193 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1194 # First do the raw seek, then empty the read buffer, so that
1195 # if the raw seek fails, we don't lose buffered data forever.
1196 pos = self.raw.seek(pos, whence)
1197 with self._read_lock:
1198 self._reset_read_buf()
1199 if pos < 0:
1200 raise IOError("seek() returned invalid position")
1201 return pos
1202
1203 def tell(self):
1204 if self._write_buf:
1205 return BufferedWriter.tell(self)
1206 else:
1207 return BufferedReader.tell(self)
1208
1209 def truncate(self, pos=None):
1210 if pos is None:
1211 pos = self.tell()
1212 # Use seek to flush the read buffer.
Antoine Pitrou66f9fea2010-01-31 23:20:26 +00001213 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001214
1215 def read(self, n=None):
1216 if n is None:
1217 n = -1
1218 self.flush()
1219 return BufferedReader.read(self, n)
1220
1221 def readinto(self, b):
1222 self.flush()
1223 return BufferedReader.readinto(self, b)
1224
1225 def peek(self, n=0):
1226 self.flush()
1227 return BufferedReader.peek(self, n)
1228
1229 def read1(self, n):
1230 self.flush()
1231 return BufferedReader.read1(self, n)
1232
1233 def write(self, b):
1234 if self._read_buf:
1235 # Undo readahead
1236 with self._read_lock:
1237 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1238 self._reset_read_buf()
1239 return BufferedWriter.write(self, b)
1240
1241
1242class TextIOBase(IOBase):
1243
1244 """Base class for text I/O.
1245
1246 This class provides a character and line based interface to stream
1247 I/O. There is no readinto method because Python's character strings
1248 are immutable. There is no public constructor.
1249 """
1250
1251 def read(self, n: int = -1) -> str:
1252 """Read at most n characters from stream.
1253
1254 Read from underlying buffer until we have n characters or we hit EOF.
1255 If n is negative or omitted, read until EOF.
1256 """
1257 self._unsupported("read")
1258
1259 def write(self, s: str) -> int:
1260 """Write string s to stream."""
1261 self._unsupported("write")
1262
1263 def truncate(self, pos: int = None) -> int:
1264 """Truncate size to pos."""
1265 self._unsupported("truncate")
1266
1267 def readline(self) -> str:
1268 """Read until newline or EOF.
1269
1270 Returns an empty string if EOF is hit immediately.
1271 """
1272 self._unsupported("readline")
1273
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001274 def detach(self) -> None:
1275 """
1276 Separate the underlying buffer from the TextIOBase and return it.
1277
1278 After the underlying buffer has been detached, the TextIO is in an
1279 unusable state.
1280 """
1281 self._unsupported("detach")
1282
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001283 @property
1284 def encoding(self):
1285 """Subclasses should override."""
1286 return None
1287
1288 @property
1289 def newlines(self):
1290 """Line endings translated so far.
1291
1292 Only line endings translated during reading are considered.
1293
1294 Subclasses should override.
1295 """
1296 return None
1297
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001298 @property
1299 def errors(self):
1300 """Error setting of the decoder or encoder.
1301
1302 Subclasses should override."""
1303 return None
1304
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001305io.TextIOBase.register(TextIOBase)
1306
1307
1308class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1309 r"""Codec used when reading a file in universal newlines mode. It wraps
1310 another incremental decoder, translating \r\n and \r into \n. It also
1311 records the types of newlines encountered. When used with
1312 translate=False, it ensures that the newline sequence is returned in
1313 one piece.
1314 """
1315 def __init__(self, decoder, translate, errors='strict'):
1316 codecs.IncrementalDecoder.__init__(self, errors=errors)
1317 self.translate = translate
1318 self.decoder = decoder
1319 self.seennl = 0
1320 self.pendingcr = False
1321
1322 def decode(self, input, final=False):
1323 # decode input (with the eventual \r from a previous pass)
1324 if self.decoder is None:
1325 output = input
1326 else:
1327 output = self.decoder.decode(input, final=final)
1328 if self.pendingcr and (output or final):
1329 output = "\r" + output
1330 self.pendingcr = False
1331
1332 # retain last \r even when not translating data:
1333 # then readline() is sure to get \r\n in one pass
1334 if output.endswith("\r") and not final:
1335 output = output[:-1]
1336 self.pendingcr = True
1337
1338 # Record which newlines are read
1339 crlf = output.count('\r\n')
1340 cr = output.count('\r') - crlf
1341 lf = output.count('\n') - crlf
1342 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1343 | (crlf and self._CRLF)
1344
1345 if self.translate:
1346 if crlf:
1347 output = output.replace("\r\n", "\n")
1348 if cr:
1349 output = output.replace("\r", "\n")
1350
1351 return output
1352
1353 def getstate(self):
1354 if self.decoder is None:
1355 buf = b""
1356 flag = 0
1357 else:
1358 buf, flag = self.decoder.getstate()
1359 flag <<= 1
1360 if self.pendingcr:
1361 flag |= 1
1362 return buf, flag
1363
1364 def setstate(self, state):
1365 buf, flag = state
1366 self.pendingcr = bool(flag & 1)
1367 if self.decoder is not None:
1368 self.decoder.setstate((buf, flag >> 1))
1369
1370 def reset(self):
1371 self.seennl = 0
1372 self.pendingcr = False
1373 if self.decoder is not None:
1374 self.decoder.reset()
1375
1376 _LF = 1
1377 _CR = 2
1378 _CRLF = 4
1379
1380 @property
1381 def newlines(self):
1382 return (None,
1383 "\n",
1384 "\r",
1385 ("\r", "\n"),
1386 "\r\n",
1387 ("\n", "\r\n"),
1388 ("\r", "\r\n"),
1389 ("\r", "\n", "\r\n")
1390 )[self.seennl]
1391
1392
1393class TextIOWrapper(TextIOBase):
1394
1395 r"""Character and line based layer over a BufferedIOBase object, buffer.
1396
1397 encoding gives the name of the encoding that the stream will be
1398 decoded or encoded with. It defaults to locale.getpreferredencoding.
1399
1400 errors determines the strictness of encoding and decoding (see the
1401 codecs.register) and defaults to "strict".
1402
1403 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1404 handling of line endings. If it is None, universal newlines is
1405 enabled. With this enabled, on input, the lines endings '\n', '\r',
1406 or '\r\n' are translated to '\n' before being returned to the
1407 caller. Conversely, on output, '\n' is translated to the system
1408 default line seperator, os.linesep. If newline is any other of its
1409 legal values, that newline becomes the newline when the file is read
1410 and it is returned untranslated. On output, '\n' is converted to the
1411 newline.
1412
1413 If line_buffering is True, a call to flush is implied when a call to
1414 write contains a newline character.
1415 """
1416
1417 _CHUNK_SIZE = 2048
1418
1419 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1420 line_buffering=False):
1421 if newline is not None and not isinstance(newline, str):
1422 raise TypeError("illegal newline type: %r" % (type(newline),))
1423 if newline not in (None, "", "\n", "\r", "\r\n"):
1424 raise ValueError("illegal newline value: %r" % (newline,))
1425 if encoding is None:
1426 try:
1427 encoding = os.device_encoding(buffer.fileno())
1428 except (AttributeError, UnsupportedOperation):
1429 pass
1430 if encoding is None:
1431 try:
1432 import locale
1433 except ImportError:
1434 # Importing locale may fail if Python is being built
1435 encoding = "ascii"
1436 else:
1437 encoding = locale.getpreferredencoding()
1438
1439 if not isinstance(encoding, str):
1440 raise ValueError("invalid encoding: %r" % encoding)
1441
1442 if errors is None:
1443 errors = "strict"
1444 else:
1445 if not isinstance(errors, str):
1446 raise ValueError("invalid errors: %r" % errors)
1447
1448 self.buffer = buffer
1449 self._line_buffering = line_buffering
1450 self._encoding = encoding
1451 self._errors = errors
1452 self._readuniversal = not newline
1453 self._readtranslate = newline is None
1454 self._readnl = newline
1455 self._writetranslate = newline != ''
1456 self._writenl = newline or os.linesep
1457 self._encoder = None
1458 self._decoder = None
1459 self._decoded_chars = '' # buffer for text returned from decoder
1460 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1461 self._snapshot = None # info for reconstructing decoder state
1462 self._seekable = self._telling = self.buffer.seekable()
1463
Antoine Pitroue4501852009-05-14 18:55:55 +00001464 if self._seekable and self.writable():
1465 position = self.buffer.tell()
1466 if position != 0:
1467 try:
1468 self._get_encoder().setstate(0)
1469 except LookupError:
1470 # Sometimes the encoder doesn't exist
1471 pass
1472
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001473 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1474 # where dec_flags is the second (integer) item of the decoder state
1475 # and next_input is the chunk of input bytes that comes next after the
1476 # snapshot point. We use this to reconstruct decoder states in tell().
1477
1478 # Naming convention:
1479 # - "bytes_..." for integer variables that count input bytes
1480 # - "chars_..." for integer variables that count decoded characters
1481
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001482 def __repr__(self):
Antoine Pitrou716c4442009-05-23 19:04:03 +00001483 try:
1484 name = self.name
1485 except AttributeError:
1486 return "<_pyio.TextIOWrapper encoding={0!r}>".format(self.encoding)
1487 else:
1488 return "<_pyio.TextIOWrapper name={0!r} encoding={1!r}>".format(
1489 name, self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001490
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001491 @property
1492 def encoding(self):
1493 return self._encoding
1494
1495 @property
1496 def errors(self):
1497 return self._errors
1498
1499 @property
1500 def line_buffering(self):
1501 return self._line_buffering
1502
1503 def seekable(self):
1504 return self._seekable
1505
1506 def readable(self):
1507 return self.buffer.readable()
1508
1509 def writable(self):
1510 return self.buffer.writable()
1511
1512 def flush(self):
1513 self.buffer.flush()
1514 self._telling = self._seekable
1515
1516 def close(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001517 if self.buffer is not None:
1518 try:
1519 self.flush()
1520 except IOError:
1521 pass # If flush() fails, just give up
1522 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001523
1524 @property
1525 def closed(self):
1526 return self.buffer.closed
1527
1528 @property
1529 def name(self):
1530 return self.buffer.name
1531
1532 def fileno(self):
1533 return self.buffer.fileno()
1534
1535 def isatty(self):
1536 return self.buffer.isatty()
1537
1538 def write(self, s: str):
1539 if self.closed:
1540 raise ValueError("write to closed file")
1541 if not isinstance(s, str):
1542 raise TypeError("can't write %s to text stream" %
1543 s.__class__.__name__)
1544 length = len(s)
1545 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1546 if haslf and self._writetranslate and self._writenl != "\n":
1547 s = s.replace("\n", self._writenl)
1548 encoder = self._encoder or self._get_encoder()
1549 # XXX What if we were just reading?
1550 b = encoder.encode(s)
1551 self.buffer.write(b)
1552 if self._line_buffering and (haslf or "\r" in s):
1553 self.flush()
1554 self._snapshot = None
1555 if self._decoder:
1556 self._decoder.reset()
1557 return length
1558
1559 def _get_encoder(self):
1560 make_encoder = codecs.getincrementalencoder(self._encoding)
1561 self._encoder = make_encoder(self._errors)
1562 return self._encoder
1563
1564 def _get_decoder(self):
1565 make_decoder = codecs.getincrementaldecoder(self._encoding)
1566 decoder = make_decoder(self._errors)
1567 if self._readuniversal:
1568 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1569 self._decoder = decoder
1570 return decoder
1571
1572 # The following three methods implement an ADT for _decoded_chars.
1573 # Text returned from the decoder is buffered here until the client
1574 # requests it by calling our read() or readline() method.
1575 def _set_decoded_chars(self, chars):
1576 """Set the _decoded_chars buffer."""
1577 self._decoded_chars = chars
1578 self._decoded_chars_used = 0
1579
1580 def _get_decoded_chars(self, n=None):
1581 """Advance into the _decoded_chars buffer."""
1582 offset = self._decoded_chars_used
1583 if n is None:
1584 chars = self._decoded_chars[offset:]
1585 else:
1586 chars = self._decoded_chars[offset:offset + n]
1587 self._decoded_chars_used += len(chars)
1588 return chars
1589
1590 def _rewind_decoded_chars(self, n):
1591 """Rewind the _decoded_chars buffer."""
1592 if self._decoded_chars_used < n:
1593 raise AssertionError("rewind decoded_chars out of bounds")
1594 self._decoded_chars_used -= n
1595
1596 def _read_chunk(self):
1597 """
1598 Read and decode the next chunk of data from the BufferedReader.
1599 """
1600
1601 # The return value is True unless EOF was reached. The decoded
1602 # string is placed in self._decoded_chars (replacing its previous
1603 # value). The entire input chunk is sent to the decoder, though
1604 # some of it may remain buffered in the decoder, yet to be
1605 # converted.
1606
1607 if self._decoder is None:
1608 raise ValueError("no decoder")
1609
1610 if self._telling:
1611 # To prepare for tell(), we need to snapshot a point in the
1612 # file where the decoder's input buffer is empty.
1613
1614 dec_buffer, dec_flags = self._decoder.getstate()
1615 # Given this, we know there was a valid snapshot point
1616 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1617
1618 # Read a chunk, decode it, and put the result in self._decoded_chars.
1619 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1620 eof = not input_chunk
1621 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
1622
1623 if self._telling:
1624 # At the snapshot point, len(dec_buffer) bytes before the read,
1625 # the next input to be decoded is dec_buffer + input_chunk.
1626 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1627
1628 return not eof
1629
1630 def _pack_cookie(self, position, dec_flags=0,
1631 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1632 # The meaning of a tell() cookie is: seek to position, set the
1633 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1634 # into the decoder with need_eof as the EOF flag, then skip
1635 # chars_to_skip characters of the decoded result. For most simple
1636 # decoders, tell() will often just give a byte offset in the file.
1637 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1638 (chars_to_skip<<192) | bool(need_eof)<<256)
1639
1640 def _unpack_cookie(self, bigint):
1641 rest, position = divmod(bigint, 1<<64)
1642 rest, dec_flags = divmod(rest, 1<<64)
1643 rest, bytes_to_feed = divmod(rest, 1<<64)
1644 need_eof, chars_to_skip = divmod(rest, 1<<64)
1645 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1646
1647 def tell(self):
1648 if not self._seekable:
1649 raise IOError("underlying stream is not seekable")
1650 if not self._telling:
1651 raise IOError("telling position disabled by next() call")
1652 self.flush()
1653 position = self.buffer.tell()
1654 decoder = self._decoder
1655 if decoder is None or self._snapshot is None:
1656 if self._decoded_chars:
1657 # This should never happen.
1658 raise AssertionError("pending decoded text")
1659 return position
1660
1661 # Skip backward to the snapshot point (see _read_chunk).
1662 dec_flags, next_input = self._snapshot
1663 position -= len(next_input)
1664
1665 # How many decoded characters have been used up since the snapshot?
1666 chars_to_skip = self._decoded_chars_used
1667 if chars_to_skip == 0:
1668 # We haven't moved from the snapshot point.
1669 return self._pack_cookie(position, dec_flags)
1670
1671 # Starting from the snapshot position, we will walk the decoder
1672 # forward until it gives us enough decoded characters.
1673 saved_state = decoder.getstate()
1674 try:
1675 # Note our initial start point.
1676 decoder.setstate((b'', dec_flags))
1677 start_pos = position
1678 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1679 need_eof = 0
1680
1681 # Feed the decoder one byte at a time. As we go, note the
1682 # nearest "safe start point" before the current location
1683 # (a point where the decoder has nothing buffered, so seek()
1684 # can safely start from there and advance to this location).
1685 next_byte = bytearray(1)
1686 for next_byte[0] in next_input:
1687 bytes_fed += 1
1688 chars_decoded += len(decoder.decode(next_byte))
1689 dec_buffer, dec_flags = decoder.getstate()
1690 if not dec_buffer and chars_decoded <= chars_to_skip:
1691 # Decoder buffer is empty, so this is a safe start point.
1692 start_pos += bytes_fed
1693 chars_to_skip -= chars_decoded
1694 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1695 if chars_decoded >= chars_to_skip:
1696 break
1697 else:
1698 # We didn't get enough decoded data; signal EOF to get more.
1699 chars_decoded += len(decoder.decode(b'', final=True))
1700 need_eof = 1
1701 if chars_decoded < chars_to_skip:
1702 raise IOError("can't reconstruct logical file position")
1703
1704 # The returned cookie corresponds to the last safe start point.
1705 return self._pack_cookie(
1706 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1707 finally:
1708 decoder.setstate(saved_state)
1709
1710 def truncate(self, pos=None):
1711 self.flush()
1712 if pos is None:
1713 pos = self.tell()
Antoine Pitrou66f9fea2010-01-31 23:20:26 +00001714 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001715
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001716 def detach(self):
1717 if self.buffer is None:
1718 raise ValueError("buffer is already detached")
1719 self.flush()
1720 buffer = self.buffer
1721 self.buffer = None
1722 return buffer
1723
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001724 def seek(self, cookie, whence=0):
1725 if self.closed:
1726 raise ValueError("tell on closed file")
1727 if not self._seekable:
1728 raise IOError("underlying stream is not seekable")
1729 if whence == 1: # seek relative to current position
1730 if cookie != 0:
1731 raise IOError("can't do nonzero cur-relative seeks")
1732 # Seeking to the current position should attempt to
1733 # sync the underlying buffer with the current position.
1734 whence = 0
1735 cookie = self.tell()
1736 if whence == 2: # seek relative to end of file
1737 if cookie != 0:
1738 raise IOError("can't do nonzero end-relative seeks")
1739 self.flush()
1740 position = self.buffer.seek(0, 2)
1741 self._set_decoded_chars('')
1742 self._snapshot = None
1743 if self._decoder:
1744 self._decoder.reset()
1745 return position
1746 if whence != 0:
1747 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
1748 (whence,))
1749 if cookie < 0:
1750 raise ValueError("negative seek position %r" % (cookie,))
1751 self.flush()
1752
1753 # The strategy of seek() is to go back to the safe start point
1754 # and replay the effect of read(chars_to_skip) from there.
1755 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1756 self._unpack_cookie(cookie)
1757
1758 # Seek back to the safe start point.
1759 self.buffer.seek(start_pos)
1760 self._set_decoded_chars('')
1761 self._snapshot = None
1762
1763 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001764 if cookie == 0 and self._decoder:
1765 self._decoder.reset()
1766 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001767 self._decoder = self._decoder or self._get_decoder()
1768 self._decoder.setstate((b'', dec_flags))
1769 self._snapshot = (dec_flags, b'')
1770
1771 if chars_to_skip:
1772 # Just like _read_chunk, feed the decoder and save a snapshot.
1773 input_chunk = self.buffer.read(bytes_to_feed)
1774 self._set_decoded_chars(
1775 self._decoder.decode(input_chunk, need_eof))
1776 self._snapshot = (dec_flags, input_chunk)
1777
1778 # Skip chars_to_skip of the decoded characters.
1779 if len(self._decoded_chars) < chars_to_skip:
1780 raise IOError("can't restore logical file position")
1781 self._decoded_chars_used = chars_to_skip
1782
Antoine Pitroue4501852009-05-14 18:55:55 +00001783 # Finally, reset the encoder (merely useful for proper BOM handling)
1784 try:
1785 encoder = self._encoder or self._get_encoder()
1786 except LookupError:
1787 # Sometimes the encoder doesn't exist
1788 pass
1789 else:
1790 if cookie != 0:
1791 encoder.setstate(0)
1792 else:
1793 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001794 return cookie
1795
1796 def read(self, n=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00001797 self._checkReadable()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001798 if n is None:
1799 n = -1
1800 decoder = self._decoder or self._get_decoder()
1801 if n < 0:
1802 # Read everything.
1803 result = (self._get_decoded_chars() +
1804 decoder.decode(self.buffer.read(), final=True))
1805 self._set_decoded_chars('')
1806 self._snapshot = None
1807 return result
1808 else:
1809 # Keep reading chunks until we have n characters to return.
1810 eof = False
1811 result = self._get_decoded_chars(n)
1812 while len(result) < n and not eof:
1813 eof = not self._read_chunk()
1814 result += self._get_decoded_chars(n - len(result))
1815 return result
1816
1817 def __next__(self):
1818 self._telling = False
1819 line = self.readline()
1820 if not line:
1821 self._snapshot = None
1822 self._telling = self._seekable
1823 raise StopIteration
1824 return line
1825
1826 def readline(self, limit=None):
1827 if self.closed:
1828 raise ValueError("read from closed file")
1829 if limit is None:
1830 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +00001831 elif not isinstance(limit, int):
1832 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001833
1834 # Grab all the decoded text (we will rewind any extra bits later).
1835 line = self._get_decoded_chars()
1836
1837 start = 0
1838 # Make the decoder if it doesn't already exist.
1839 if not self._decoder:
1840 self._get_decoder()
1841
1842 pos = endpos = None
1843 while True:
1844 if self._readtranslate:
1845 # Newlines are already translated, only search for \n
1846 pos = line.find('\n', start)
1847 if pos >= 0:
1848 endpos = pos + 1
1849 break
1850 else:
1851 start = len(line)
1852
1853 elif self._readuniversal:
1854 # Universal newline search. Find any of \r, \r\n, \n
1855 # The decoder ensures that \r\n are not split in two pieces
1856
1857 # In C we'd look for these in parallel of course.
1858 nlpos = line.find("\n", start)
1859 crpos = line.find("\r", start)
1860 if crpos == -1:
1861 if nlpos == -1:
1862 # Nothing found
1863 start = len(line)
1864 else:
1865 # Found \n
1866 endpos = nlpos + 1
1867 break
1868 elif nlpos == -1:
1869 # Found lone \r
1870 endpos = crpos + 1
1871 break
1872 elif nlpos < crpos:
1873 # Found \n
1874 endpos = nlpos + 1
1875 break
1876 elif nlpos == crpos + 1:
1877 # Found \r\n
1878 endpos = crpos + 2
1879 break
1880 else:
1881 # Found \r
1882 endpos = crpos + 1
1883 break
1884 else:
1885 # non-universal
1886 pos = line.find(self._readnl)
1887 if pos >= 0:
1888 endpos = pos + len(self._readnl)
1889 break
1890
1891 if limit >= 0 and len(line) >= limit:
1892 endpos = limit # reached length limit
1893 break
1894
1895 # No line ending seen yet - get more data'
1896 while self._read_chunk():
1897 if self._decoded_chars:
1898 break
1899 if self._decoded_chars:
1900 line += self._get_decoded_chars()
1901 else:
1902 # end of file
1903 self._set_decoded_chars('')
1904 self._snapshot = None
1905 return line
1906
1907 if limit >= 0 and endpos > limit:
1908 endpos = limit # don't exceed limit
1909
1910 # Rewind _decoded_chars to just after the line ending we found.
1911 self._rewind_decoded_chars(len(line) - endpos)
1912 return line[:endpos]
1913
1914 @property
1915 def newlines(self):
1916 return self._decoder.newlines if self._decoder else None
1917
1918
1919class StringIO(TextIOWrapper):
1920 """Text I/O implementation using an in-memory buffer.
1921
1922 The initial_value argument sets the value of object. The newline
1923 argument is like the one of TextIOWrapper's constructor.
1924 """
1925
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001926 def __init__(self, initial_value="", newline="\n"):
1927 super(StringIO, self).__init__(BytesIO(),
1928 encoding="utf-8",
1929 errors="strict",
1930 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00001931 # Issue #5645: make universal newlines semantics the same as in the
1932 # C version, even under Windows.
1933 if newline is None:
1934 self._writetranslate = False
Georg Brandl194da4a2009-08-13 09:34:05 +00001935 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001936 if not isinstance(initial_value, str):
Georg Brandl194da4a2009-08-13 09:34:05 +00001937 raise TypeError("initial_value must be str or None, not {0}"
1938 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001939 initial_value = str(initial_value)
1940 self.write(initial_value)
1941 self.seek(0)
1942
1943 def getvalue(self):
1944 self.flush()
1945 return self.buffer.getvalue().decode(self._encoding, self._errors)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00001946
1947 def __repr__(self):
1948 # TextIOWrapper tells the encoding in its repr. In StringIO,
1949 # that's a implementation detail.
1950 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00001951
1952 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001953 def errors(self):
1954 return None
1955
1956 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00001957 def encoding(self):
1958 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001959
1960 def detach(self):
1961 # This doesn't make sense on StringIO.
1962 self._unsupported("detach")