blob: 6b2564008cf3cc0a644a14d3dfba5b0891d897c9 [file] [log] [blame]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001"""
2Python implementation of the io module.
3"""
4
5import os
6import abc
7import codecs
Benjamin Peterson59406a92009-03-26 17:10:29 +00008import warnings
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00009# Import _thread instead of threading to reduce startup cost
10try:
11 from _thread import allocate_lock as Lock
12except ImportError:
13 from _dummy_thread import allocate_lock as Lock
14
15import io
Benjamin Petersonc3be11a2010-04-27 21:24:03 +000016from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000017
18# open() uses st_blksize whenever we can
19DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
20
21# NOTE: Base classes defined here are registered with the "official" ABCs
22# defined in io.py. We don't use real inheritance though, because we don't
23# want to inherit the C implementations.
24
25
26class BlockingIOError(IOError):
27
28 """Exception raised when I/O would block on a non-blocking I/O stream."""
29
30 def __init__(self, errno, strerror, characters_written=0):
31 super().__init__(errno, strerror)
32 if not isinstance(characters_written, int):
33 raise TypeError("characters_written must be a integer")
34 self.characters_written = characters_written
35
36
Benjamin Peterson95e392c2010-04-27 21:07:21 +000037def open(file: (str, bytes), mode: str = "r", buffering: int = -1,
Benjamin Peterson9990e8c2009-04-18 14:47:50 +000038 encoding: str = None, errors: str = None,
39 newline: str = None, closefd: bool = True) -> "IOBase":
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000040
41 r"""Open file and return a stream. Raise IOError upon failure.
42
43 file is either a text or byte string giving the name (and the path
44 if the file isn't in the current working directory) of the file to
45 be opened or an integer file descriptor of the file to be
46 wrapped. (If a file descriptor is given, it is closed when the
47 returned I/O object is closed, unless closefd is set to False.)
48
49 mode is an optional string that specifies the mode in which the file
50 is opened. It defaults to 'r' which means open for reading in text
51 mode. Other common values are 'w' for writing (truncating the file if
52 it already exists), and 'a' for appending (which on some Unix systems,
53 means that all writes append to the end of the file regardless of the
54 current seek position). In text mode, if encoding is not specified the
55 encoding used is platform dependent. (For reading and writing raw
56 bytes use binary mode and leave encoding unspecified.) The available
57 modes are:
58
59 ========= ===============================================================
60 Character Meaning
61 --------- ---------------------------------------------------------------
62 'r' open for reading (default)
63 'w' open for writing, truncating the file first
64 'a' open for writing, appending to the end of the file if it exists
65 'b' binary mode
66 't' text mode (default)
67 '+' open a disk file for updating (reading and writing)
68 'U' universal newline mode (for backwards compatibility; unneeded
69 for new code)
70 ========= ===============================================================
71
72 The default mode is 'rt' (open for reading text). For binary random
73 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
74 'r+b' opens the file without truncation.
75
76 Python distinguishes between files opened in binary and text modes,
77 even when the underlying operating system doesn't. Files opened in
78 binary mode (appending 'b' to the mode argument) return contents as
79 bytes objects without any decoding. In text mode (the default, or when
80 't' is appended to the mode argument), the contents of the file are
81 returned as strings, the bytes having been first decoded using a
82 platform-dependent encoding or using the specified encoding if given.
83
Antoine Pitroud5587bc2009-12-19 21:08:31 +000084 buffering is an optional integer used to set the buffering policy.
85 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
86 line buffering (only usable in text mode), and an integer > 1 to indicate
87 the size of a fixed-size chunk buffer. When no buffering argument is
88 given, the default buffering policy works as follows:
89
90 * Binary files are buffered in fixed-size chunks; the size of the buffer
91 is chosen using a heuristic trying to determine the underlying device's
92 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
93 On many systems, the buffer will typically be 4096 or 8192 bytes long.
94
95 * "Interactive" text files (files for which isatty() returns True)
96 use line buffering. Other text files use the policy described above
97 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000098
99 encoding is the name of the encoding used to decode or encode the
100 file. This should only be used in text mode. The default encoding is
101 platform dependent, but any encoding supported by Python can be
102 passed. See the codecs module for the list of supported encodings.
103
104 errors is an optional string that specifies how encoding errors are to
105 be handled---this argument should not be used in binary mode. Pass
106 'strict' to raise a ValueError exception if there is an encoding error
107 (the default of None has the same effect), or pass 'ignore' to ignore
108 errors. (Note that ignoring encoding errors can lead to data loss.)
109 See the documentation for codecs.register for a list of the permitted
110 encoding error strings.
111
112 newline controls how universal newlines works (it only applies to text
113 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
114 follows:
115
116 * On input, if newline is None, universal newlines mode is
117 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
118 these are translated into '\n' before being returned to the
119 caller. If it is '', universal newline mode is enabled, but line
120 endings are returned to the caller untranslated. If it has any of
121 the other legal values, input lines are only terminated by the given
122 string, and the line ending is returned to the caller untranslated.
123
124 * On output, if newline is None, any '\n' characters written are
125 translated to the system default line separator, os.linesep. If
126 newline is '', no translation takes place. If newline is any of the
127 other legal values, any '\n' characters written are translated to
128 the given string.
129
130 If closefd is False, the underlying file descriptor will be kept open
131 when the file is closed. This does not work when a file name is given
132 and must be True in that case.
133
134 open() returns a file object whose type depends on the mode, and
135 through which the standard file operations such as reading and writing
136 are performed. When open() is used to open a file in a text mode ('w',
137 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
138 a file in a binary mode, the returned class varies: in read binary
139 mode, it returns a BufferedReader; in write binary and append binary
140 modes, it returns a BufferedWriter, and in read/write mode, it returns
141 a BufferedRandom.
142
143 It is also possible to use a string or bytearray as a file for both
144 reading and writing. For strings StringIO can be used like a file
145 opened in a text mode, and for bytes a BytesIO can be used like a file
146 opened in a binary mode.
147 """
148 if not isinstance(file, (str, bytes, int)):
149 raise TypeError("invalid file: %r" % file)
150 if not isinstance(mode, str):
151 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000152 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000153 raise TypeError("invalid buffering: %r" % buffering)
154 if encoding is not None and not isinstance(encoding, str):
155 raise TypeError("invalid encoding: %r" % encoding)
156 if errors is not None and not isinstance(errors, str):
157 raise TypeError("invalid errors: %r" % errors)
158 modes = set(mode)
159 if modes - set("arwb+tU") or len(mode) > len(modes):
160 raise ValueError("invalid mode: %r" % mode)
161 reading = "r" in modes
162 writing = "w" in modes
163 appending = "a" in modes
164 updating = "+" in modes
165 text = "t" in modes
166 binary = "b" in modes
167 if "U" in modes:
168 if writing or appending:
169 raise ValueError("can't use U and writing mode at once")
170 reading = True
171 if text and binary:
172 raise ValueError("can't have text and binary mode at once")
173 if reading + writing + appending > 1:
174 raise ValueError("can't have read/write/append mode at once")
175 if not (reading or writing or appending):
176 raise ValueError("must have exactly one of read/write/append mode")
177 if binary and encoding is not None:
178 raise ValueError("binary mode doesn't take an encoding argument")
179 if binary and errors is not None:
180 raise ValueError("binary mode doesn't take an errors argument")
181 if binary and newline is not None:
182 raise ValueError("binary mode doesn't take a newline argument")
183 raw = FileIO(file,
184 (reading and "r" or "") +
185 (writing and "w" or "") +
186 (appending and "a" or "") +
187 (updating and "+" or ""),
188 closefd)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000189 line_buffering = False
190 if buffering == 1 or buffering < 0 and raw.isatty():
191 buffering = -1
192 line_buffering = True
193 if buffering < 0:
194 buffering = DEFAULT_BUFFER_SIZE
195 try:
196 bs = os.fstat(raw.fileno()).st_blksize
197 except (os.error, AttributeError):
198 pass
199 else:
200 if bs > 1:
201 buffering = bs
202 if buffering < 0:
203 raise ValueError("invalid buffering size")
204 if buffering == 0:
205 if binary:
206 return raw
207 raise ValueError("can't have unbuffered text I/O")
208 if updating:
209 buffer = BufferedRandom(raw, buffering)
210 elif writing or appending:
211 buffer = BufferedWriter(raw, buffering)
212 elif reading:
213 buffer = BufferedReader(raw, buffering)
214 else:
215 raise ValueError("unknown mode: %r" % mode)
216 if binary:
217 return buffer
218 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
219 text.mode = mode
220 return text
221
222
223class DocDescriptor:
224 """Helper for builtins.open.__doc__
225 """
226 def __get__(self, obj, typ):
227 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000228 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000229 "errors=None, newline=None, closefd=True)\n\n" +
230 open.__doc__)
231
232class OpenWrapper:
233 """Wrapper for builtins.open
234
235 Trick so that open won't become a bound method when stored
236 as a class variable (as dbm.dumb does).
237
238 See initstdio() in Python/pythonrun.c.
239 """
240 __doc__ = DocDescriptor()
241
242 def __new__(cls, *args, **kwargs):
243 return open(*args, **kwargs)
244
245
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000246# In normal operation, both `UnsupportedOperation`s should be bound to the
247# same object.
248try:
249 UnsupportedOperation = io.UnsupportedOperation
250except AttributeError:
251 class UnsupportedOperation(ValueError, IOError):
252 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000253
254
255class IOBase(metaclass=abc.ABCMeta):
256
257 """The abstract base class for all I/O classes, acting on streams of
258 bytes. There is no public constructor.
259
260 This class provides dummy implementations for many methods that
261 derived classes can override selectively; the default implementations
262 represent a file that cannot be read, written or seeked.
263
264 Even though IOBase does not declare read, readinto, or write because
265 their signatures will vary, implementations and clients should
266 consider those methods part of the interface. Also, implementations
267 may raise a IOError when operations they do not support are called.
268
269 The basic type used for binary data read from or written to a file is
270 bytes. bytearrays are accepted too, and in some cases (such as
271 readinto) needed. Text I/O classes work with str data.
272
273 Note that calling any method (even inquiries) on a closed stream is
274 undefined. Implementations may raise IOError in this case.
275
276 IOBase (and its subclasses) support the iterator protocol, meaning
277 that an IOBase object can be iterated over yielding the lines in a
278 stream.
279
280 IOBase also supports the :keyword:`with` statement. In this example,
281 fp is closed after the suite of the with statement is complete:
282
283 with open('spam.txt', 'r') as fp:
284 fp.write('Spam and eggs!')
285 """
286
287 ### Internal ###
288
289 def _unsupported(self, name: str) -> IOError:
290 """Internal: raise an exception for unsupported operations."""
291 raise UnsupportedOperation("%s.%s() not supported" %
292 (self.__class__.__name__, name))
293
294 ### Positioning ###
295
296 def seek(self, pos: int, whence: int = 0) -> int:
297 """Change stream position.
298
299 Change the stream position to byte offset offset. offset is
300 interpreted relative to the position indicated by whence. Values
301 for whence are:
302
303 * 0 -- start of stream (the default); offset should be zero or positive
304 * 1 -- current stream position; offset may be negative
305 * 2 -- end of stream; offset is usually negative
306
307 Return the new absolute position.
308 """
309 self._unsupported("seek")
310
311 def tell(self) -> int:
312 """Return current stream position."""
313 return self.seek(0, 1)
314
315 def truncate(self, pos: int = None) -> int:
316 """Truncate file to size bytes.
317
318 Size defaults to the current IO position as reported by tell(). Return
319 the new size.
320 """
321 self._unsupported("truncate")
322
323 ### Flush and close ###
324
325 def flush(self) -> None:
326 """Flush write buffers, if applicable.
327
328 This is not implemented for read-only and non-blocking streams.
329 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000330 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000331 # XXX Should this return the number of bytes written???
332
333 __closed = False
334
335 def close(self) -> None:
336 """Flush and close the IO object.
337
338 This method has no effect if the file is already closed.
339 """
340 if not self.__closed:
Antoine Pitrou6be88762010-05-03 16:48:20 +0000341 self.flush()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000342 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():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000370 raise UnsupportedOperation("File or stream is not seekable."
371 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000372
373 def readable(self) -> bool:
374 """Return whether object was opened for reading.
375
376 If False, read() will raise IOError.
377 """
378 return False
379
380 def _checkReadable(self, msg=None):
381 """Internal: raise an IOError if file is not readable
382 """
383 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000384 raise UnsupportedOperation("File or stream is not readable."
385 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000386
387 def writable(self) -> bool:
388 """Return whether object was opened for writing.
389
390 If False, write() and truncate() will raise IOError.
391 """
392 return False
393
394 def _checkWritable(self, msg=None):
395 """Internal: raise an IOError if file is not writable
396 """
397 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000398 raise UnsupportedOperation("File or stream is not writable."
399 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000400
401 @property
402 def closed(self):
403 """closed: bool. True iff the file has been closed.
404
405 For backwards compatibility, this is a property, not a predicate.
406 """
407 return self.__closed
408
409 def _checkClosed(self, msg=None):
410 """Internal: raise an ValueError if file is closed
411 """
412 if self.closed:
413 raise ValueError("I/O operation on closed file."
414 if msg is None else msg)
415
416 ### Context manager ###
417
418 def __enter__(self) -> "IOBase": # That's a forward reference
419 """Context management protocol. Returns self."""
420 self._checkClosed()
421 return self
422
423 def __exit__(self, *args) -> None:
424 """Context management protocol. Calls close()"""
425 self.close()
426
427 ### Lower-level APIs ###
428
429 # XXX Should these be present even if unimplemented?
430
431 def fileno(self) -> int:
432 """Returns underlying file descriptor if one exists.
433
434 An IOError is raised if the IO object does not use a file descriptor.
435 """
436 self._unsupported("fileno")
437
438 def isatty(self) -> bool:
439 """Return whether this is an 'interactive' stream.
440
441 Return False if it can't be determined.
442 """
443 self._checkClosed()
444 return False
445
446 ### Readline[s] and writelines ###
447
448 def readline(self, limit: int = -1) -> bytes:
449 r"""Read and return a line from the stream.
450
451 If limit is specified, at most limit bytes will be read.
452
453 The line terminator is always b'\n' for binary files; for text
454 files, the newlines argument to open can be used to select the line
455 terminator(s) recognized.
456 """
457 # For backwards compatibility, a (slowish) readline().
458 if hasattr(self, "peek"):
459 def nreadahead():
460 readahead = self.peek(1)
461 if not readahead:
462 return 1
463 n = (readahead.find(b"\n") + 1) or len(readahead)
464 if limit >= 0:
465 n = min(n, limit)
466 return n
467 else:
468 def nreadahead():
469 return 1
470 if limit is None:
471 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +0000472 elif not isinstance(limit, int):
473 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000474 res = bytearray()
475 while limit < 0 or len(res) < limit:
476 b = self.read(nreadahead())
477 if not b:
478 break
479 res += b
480 if res.endswith(b"\n"):
481 break
482 return bytes(res)
483
484 def __iter__(self):
485 self._checkClosed()
486 return self
487
488 def __next__(self):
489 line = self.readline()
490 if not line:
491 raise StopIteration
492 return line
493
494 def readlines(self, hint=None):
495 """Return a list of lines from the stream.
496
497 hint can be specified to control the number of lines read: no more
498 lines will be read if the total size (in bytes/characters) of all
499 lines so far exceeds hint.
500 """
501 if hint is None or hint <= 0:
502 return list(self)
503 n = 0
504 lines = []
505 for line in self:
506 lines.append(line)
507 n += len(line)
508 if n >= hint:
509 break
510 return lines
511
512 def writelines(self, lines):
513 self._checkClosed()
514 for line in lines:
515 self.write(line)
516
517io.IOBase.register(IOBase)
518
519
520class RawIOBase(IOBase):
521
522 """Base class for raw binary I/O."""
523
524 # The read() method is implemented by calling readinto(); derived
525 # classes that want to support read() only need to implement
526 # readinto() as a primitive operation. In general, readinto() can be
527 # more efficient than read().
528
529 # (It would be tempting to also provide an implementation of
530 # readinto() in terms of read(), in case the latter is a more suitable
531 # primitive operation, but that would lead to nasty recursion in case
532 # a subclass doesn't implement either.)
533
534 def read(self, n: int = -1) -> bytes:
535 """Read and return up to n bytes.
536
537 Returns an empty bytes object on EOF, or None if the object is
538 set not to block and has no data to read.
539 """
540 if n is None:
541 n = -1
542 if n < 0:
543 return self.readall()
544 b = bytearray(n.__index__())
545 n = self.readinto(b)
546 del b[n:]
547 return bytes(b)
548
549 def readall(self):
550 """Read until EOF, using multiple read() call."""
551 res = bytearray()
552 while True:
553 data = self.read(DEFAULT_BUFFER_SIZE)
554 if not data:
555 break
556 res += data
557 return bytes(res)
558
559 def readinto(self, b: bytearray) -> int:
560 """Read up to len(b) bytes into b.
561
562 Returns number of bytes read (0 for EOF), or None if the object
563 is set not to block as has no data to read.
564 """
565 self._unsupported("readinto")
566
567 def write(self, b: bytes) -> int:
568 """Write the given buffer to the IO stream.
569
570 Returns the number of bytes written, which may be less than len(b).
571 """
572 self._unsupported("write")
573
574io.RawIOBase.register(RawIOBase)
575from _io import FileIO
576RawIOBase.register(FileIO)
577
578
579class BufferedIOBase(IOBase):
580
581 """Base class for buffered IO objects.
582
583 The main difference with RawIOBase is that the read() method
584 supports omitting the size argument, and does not have a default
585 implementation that defers to readinto().
586
587 In addition, read(), readinto() and write() may raise
588 BlockingIOError if the underlying raw stream is in non-blocking
589 mode and not ready; unlike their raw counterparts, they will never
590 return None.
591
592 A typical implementation should not inherit from a RawIOBase
593 implementation, but wrap one.
594 """
595
596 def read(self, n: int = None) -> bytes:
597 """Read and return up to n bytes.
598
599 If the argument is omitted, None, or negative, reads and
600 returns all data until EOF.
601
602 If the argument is positive, and the underlying raw stream is
603 not 'interactive', multiple raw reads may be issued to satisfy
604 the byte count (unless EOF is reached first). But for
605 interactive raw streams (XXX and for pipes?), at most one raw
606 read will be issued, and a short result does not imply that
607 EOF is imminent.
608
609 Returns an empty bytes array on EOF.
610
611 Raises BlockingIOError if the underlying raw stream has no
612 data at the moment.
613 """
614 self._unsupported("read")
615
616 def read1(self, n: int=None) -> bytes:
617 """Read up to n bytes with at most one read() system call."""
618 self._unsupported("read1")
619
620 def readinto(self, b: bytearray) -> int:
621 """Read up to len(b) bytes into b.
622
623 Like read(), this may issue multiple reads to the underlying raw
624 stream, unless the latter is 'interactive'.
625
626 Returns the number of bytes read (0 for EOF).
627
628 Raises BlockingIOError if the underlying raw stream has no
629 data at the moment.
630 """
631 # XXX This ought to work with anything that supports the buffer API
632 data = self.read(len(b))
633 n = len(data)
634 try:
635 b[:n] = data
636 except TypeError as err:
637 import array
638 if not isinstance(b, array.array):
639 raise err
640 b[:n] = array.array('b', data)
641 return n
642
643 def write(self, b: bytes) -> int:
644 """Write the given buffer to the IO stream.
645
646 Return the number of bytes written, which is never less than
647 len(b).
648
649 Raises BlockingIOError if the buffer is full and the
650 underlying raw stream cannot accept more data at the moment.
651 """
652 self._unsupported("write")
653
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000654 def detach(self) -> None:
655 """
656 Separate the underlying raw stream from the buffer and return it.
657
658 After the raw stream has been detached, the buffer is in an unusable
659 state.
660 """
661 self._unsupported("detach")
662
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000663io.BufferedIOBase.register(BufferedIOBase)
664
665
666class _BufferedIOMixin(BufferedIOBase):
667
668 """A mixin implementation of BufferedIOBase with an underlying raw stream.
669
670 This passes most requests on to the underlying raw stream. It
671 does *not* provide implementations of read(), readinto() or
672 write().
673 """
674
675 def __init__(self, raw):
676 self.raw = raw
677
678 ### Positioning ###
679
680 def seek(self, pos, whence=0):
681 new_position = self.raw.seek(pos, whence)
682 if new_position < 0:
683 raise IOError("seek() returned an invalid position")
684 return new_position
685
686 def tell(self):
687 pos = self.raw.tell()
688 if pos < 0:
689 raise IOError("tell() returned an invalid position")
690 return pos
691
692 def truncate(self, pos=None):
693 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
694 # and a flush may be necessary to synch both views of the current
695 # file state.
696 self.flush()
697
698 if pos is None:
699 pos = self.tell()
700 # XXX: Should seek() be used, instead of passing the position
701 # XXX directly to truncate?
702 return self.raw.truncate(pos)
703
704 ### Flush and close ###
705
706 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000707 if self.closed:
708 raise ValueError("flush of closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000709 self.raw.flush()
710
711 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000712 if self.raw is not None and not self.closed:
713 self.flush()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000714 self.raw.close()
715
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000716 def detach(self):
717 if self.raw is None:
718 raise ValueError("raw stream already detached")
719 self.flush()
720 raw = self.raw
721 self.raw = None
722 return raw
723
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000724 ### Inquiries ###
725
726 def seekable(self):
727 return self.raw.seekable()
728
729 def readable(self):
730 return self.raw.readable()
731
732 def writable(self):
733 return self.raw.writable()
734
735 @property
736 def closed(self):
737 return self.raw.closed
738
739 @property
740 def name(self):
741 return self.raw.name
742
743 @property
744 def mode(self):
745 return self.raw.mode
746
Antoine Pitrou716c4442009-05-23 19:04:03 +0000747 def __repr__(self):
748 clsname = self.__class__.__name__
749 try:
750 name = self.name
751 except AttributeError:
752 return "<_pyio.{0}>".format(clsname)
753 else:
754 return "<_pyio.{0} name={1!r}>".format(clsname, name)
755
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000756 ### Lower-level APIs ###
757
758 def fileno(self):
759 return self.raw.fileno()
760
761 def isatty(self):
762 return self.raw.isatty()
763
764
765class BytesIO(BufferedIOBase):
766
767 """Buffered I/O implementation using an in-memory bytes buffer."""
768
769 def __init__(self, initial_bytes=None):
770 buf = bytearray()
771 if initial_bytes is not None:
772 buf += initial_bytes
773 self._buffer = buf
774 self._pos = 0
775
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000776 def __getstate__(self):
777 if self.closed:
778 raise ValueError("__getstate__ on closed file")
779 return self.__dict__.copy()
780
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000781 def getvalue(self):
782 """Return the bytes value (contents) of the buffer
783 """
784 if self.closed:
785 raise ValueError("getvalue on closed file")
786 return bytes(self._buffer)
787
Antoine Pitrou972ee132010-09-06 18:48:21 +0000788 def getbuffer(self):
789 """Return a readable and writable view of the buffer.
790 """
791 return memoryview(self._buffer)
792
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000793 def read(self, n=None):
794 if self.closed:
795 raise ValueError("read from closed file")
796 if n is None:
797 n = -1
798 if n < 0:
799 n = len(self._buffer)
800 if len(self._buffer) <= self._pos:
801 return b""
802 newpos = min(len(self._buffer), self._pos + n)
803 b = self._buffer[self._pos : newpos]
804 self._pos = newpos
805 return bytes(b)
806
807 def read1(self, n):
808 """This is the same as read.
809 """
810 return self.read(n)
811
812 def write(self, b):
813 if self.closed:
814 raise ValueError("write to closed file")
815 if isinstance(b, str):
816 raise TypeError("can't write str to binary stream")
817 n = len(b)
818 if n == 0:
819 return 0
820 pos = self._pos
821 if pos > len(self._buffer):
822 # Inserts null bytes between the current end of the file
823 # and the new write position.
824 padding = b'\x00' * (pos - len(self._buffer))
825 self._buffer += padding
826 self._buffer[pos:pos + n] = b
827 self._pos += n
828 return n
829
830 def seek(self, pos, whence=0):
831 if self.closed:
832 raise ValueError("seek on closed file")
833 try:
Florent Xiclunab14930c2010-03-13 15:26:44 +0000834 pos.__index__
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000835 except AttributeError as err:
836 raise TypeError("an integer is required") from err
837 if whence == 0:
838 if pos < 0:
839 raise ValueError("negative seek position %r" % (pos,))
840 self._pos = pos
841 elif whence == 1:
842 self._pos = max(0, self._pos + pos)
843 elif whence == 2:
844 self._pos = max(0, len(self._buffer) + pos)
845 else:
846 raise ValueError("invalid whence value")
847 return self._pos
848
849 def tell(self):
850 if self.closed:
851 raise ValueError("tell on closed file")
852 return self._pos
853
854 def truncate(self, pos=None):
855 if self.closed:
856 raise ValueError("truncate on closed file")
857 if pos is None:
858 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000859 else:
860 try:
861 pos.__index__
862 except AttributeError as err:
863 raise TypeError("an integer is required") from err
864 if pos < 0:
865 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000866 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000867 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000868
869 def readable(self):
870 return True
871
872 def writable(self):
873 return True
874
875 def seekable(self):
876 return True
877
878
879class BufferedReader(_BufferedIOMixin):
880
881 """BufferedReader(raw[, buffer_size])
882
883 A buffer for a readable, sequential BaseRawIO object.
884
885 The constructor creates a BufferedReader for the given readable raw
886 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
887 is used.
888 """
889
890 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
891 """Create a new buffered reader using the given readable raw IO object.
892 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000893 if not raw.readable():
894 raise IOError('"raw" argument must be readable.')
895
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000896 _BufferedIOMixin.__init__(self, raw)
897 if buffer_size <= 0:
898 raise ValueError("invalid buffer size")
899 self.buffer_size = buffer_size
900 self._reset_read_buf()
901 self._read_lock = Lock()
902
903 def _reset_read_buf(self):
904 self._read_buf = b""
905 self._read_pos = 0
906
907 def read(self, n=None):
908 """Read n bytes.
909
910 Returns exactly n bytes of data unless the underlying raw IO
911 stream reaches EOF or if the call would block in non-blocking
912 mode. If n is negative, read until EOF or until read() would
913 block.
914 """
915 if n is not None and n < -1:
916 raise ValueError("invalid number of bytes to read")
917 with self._read_lock:
918 return self._read_unlocked(n)
919
920 def _read_unlocked(self, n=None):
921 nodata_val = b""
922 empty_values = (b"", None)
923 buf = self._read_buf
924 pos = self._read_pos
925
926 # Special case for when the number of bytes to read is unspecified.
927 if n is None or n == -1:
928 self._reset_read_buf()
929 chunks = [buf[pos:]] # Strip the consumed bytes.
930 current_size = 0
931 while True:
932 # Read until EOF or until read() would block.
933 chunk = self.raw.read()
934 if chunk in empty_values:
935 nodata_val = chunk
936 break
937 current_size += len(chunk)
938 chunks.append(chunk)
939 return b"".join(chunks) or nodata_val
940
941 # The number of bytes to read is specified, return at most n bytes.
942 avail = len(buf) - pos # Length of the available buffered data.
943 if n <= avail:
944 # Fast path: the data to read is fully buffered.
945 self._read_pos += n
946 return buf[pos:pos+n]
947 # Slow path: read from the stream until enough bytes are read,
948 # or until an EOF occurs or until read() would block.
949 chunks = [buf[pos:]]
950 wanted = max(self.buffer_size, n)
951 while avail < n:
952 chunk = self.raw.read(wanted)
953 if chunk in empty_values:
954 nodata_val = chunk
955 break
956 avail += len(chunk)
957 chunks.append(chunk)
958 # n is more then avail only when an EOF occurred or when
959 # read() would have blocked.
960 n = min(n, avail)
961 out = b"".join(chunks)
962 self._read_buf = out[n:] # Save the extra data in the buffer.
963 self._read_pos = 0
964 return out[:n] if out else nodata_val
965
966 def peek(self, n=0):
967 """Returns buffered bytes without advancing the position.
968
969 The argument indicates a desired minimal number of bytes; we
970 do at most one raw read to satisfy it. We never return more
971 than self.buffer_size.
972 """
973 with self._read_lock:
974 return self._peek_unlocked(n)
975
976 def _peek_unlocked(self, n=0):
977 want = min(n, self.buffer_size)
978 have = len(self._read_buf) - self._read_pos
979 if have < want or have <= 0:
980 to_read = self.buffer_size - have
981 current = self.raw.read(to_read)
982 if current:
983 self._read_buf = self._read_buf[self._read_pos:] + current
984 self._read_pos = 0
985 return self._read_buf[self._read_pos:]
986
987 def read1(self, n):
988 """Reads up to n bytes, with at most one read() system call."""
989 # Returns up to n bytes. If at least one byte is buffered, we
990 # only return buffered bytes. Otherwise, we do one raw read.
991 if n < 0:
992 raise ValueError("number of bytes to read must be positive")
993 if n == 0:
994 return b""
995 with self._read_lock:
996 self._peek_unlocked(1)
997 return self._read_unlocked(
998 min(n, len(self._read_buf) - self._read_pos))
999
1000 def tell(self):
1001 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1002
1003 def seek(self, pos, whence=0):
1004 if not (0 <= whence <= 2):
1005 raise ValueError("invalid whence value")
1006 with self._read_lock:
1007 if whence == 1:
1008 pos -= len(self._read_buf) - self._read_pos
1009 pos = _BufferedIOMixin.seek(self, pos, whence)
1010 self._reset_read_buf()
1011 return pos
1012
1013class BufferedWriter(_BufferedIOMixin):
1014
1015 """A buffer for a writeable sequential RawIO object.
1016
1017 The constructor creates a BufferedWriter for the given writeable raw
1018 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001019 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001020 """
1021
Benjamin Peterson59406a92009-03-26 17:10:29 +00001022 _warning_stack_offset = 2
1023
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001024 def __init__(self, raw,
1025 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001026 if not raw.writable():
1027 raise IOError('"raw" argument must be writable.')
1028
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001029 _BufferedIOMixin.__init__(self, raw)
1030 if buffer_size <= 0:
1031 raise ValueError("invalid buffer size")
Benjamin Peterson59406a92009-03-26 17:10:29 +00001032 if max_buffer_size is not None:
1033 warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
1034 self._warning_stack_offset)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001035 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001036 self._write_buf = bytearray()
1037 self._write_lock = Lock()
1038
1039 def write(self, b):
1040 if self.closed:
1041 raise ValueError("write to closed file")
1042 if isinstance(b, str):
1043 raise TypeError("can't write str to binary stream")
1044 with self._write_lock:
1045 # XXX we can implement some more tricks to try and avoid
1046 # partial writes
1047 if len(self._write_buf) > self.buffer_size:
1048 # We're full, so let's pre-flush the buffer
1049 try:
1050 self._flush_unlocked()
1051 except BlockingIOError as e:
1052 # We can't accept anything else.
1053 # XXX Why not just let the exception pass through?
1054 raise BlockingIOError(e.errno, e.strerror, 0)
1055 before = len(self._write_buf)
1056 self._write_buf.extend(b)
1057 written = len(self._write_buf) - before
1058 if len(self._write_buf) > self.buffer_size:
1059 try:
1060 self._flush_unlocked()
1061 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001062 if len(self._write_buf) > self.buffer_size:
1063 # We've hit the buffer_size. We have to accept a partial
1064 # write and cut back our buffer.
1065 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001066 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001067 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001068 raise BlockingIOError(e.errno, e.strerror, written)
1069 return written
1070
1071 def truncate(self, pos=None):
1072 with self._write_lock:
1073 self._flush_unlocked()
1074 if pos is None:
1075 pos = self.raw.tell()
1076 return self.raw.truncate(pos)
1077
1078 def flush(self):
1079 with self._write_lock:
1080 self._flush_unlocked()
1081
1082 def _flush_unlocked(self):
1083 if self.closed:
1084 raise ValueError("flush of closed file")
1085 written = 0
1086 try:
1087 while self._write_buf:
1088 n = self.raw.write(self._write_buf)
1089 if n > len(self._write_buf) or n < 0:
1090 raise IOError("write() returned incorrect number of bytes")
1091 del self._write_buf[:n]
1092 written += n
1093 except BlockingIOError as e:
1094 n = e.characters_written
1095 del self._write_buf[:n]
1096 written += n
1097 raise BlockingIOError(e.errno, e.strerror, written)
1098
1099 def tell(self):
1100 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1101
1102 def seek(self, pos, whence=0):
1103 if not (0 <= whence <= 2):
1104 raise ValueError("invalid whence")
1105 with self._write_lock:
1106 self._flush_unlocked()
1107 return _BufferedIOMixin.seek(self, pos, whence)
1108
1109
1110class BufferedRWPair(BufferedIOBase):
1111
1112 """A buffered reader and writer object together.
1113
1114 A buffered reader object and buffered writer object put together to
1115 form a sequential IO object that can read and write. This is typically
1116 used with a socket or two-way pipe.
1117
1118 reader and writer are RawIOBase objects that are readable and
1119 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001120 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001121 """
1122
1123 # XXX The usefulness of this (compared to having two separate IO
1124 # objects) is questionable.
1125
1126 def __init__(self, reader, writer,
1127 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1128 """Constructor.
1129
1130 The arguments are two RawIO instances.
1131 """
Benjamin Peterson59406a92009-03-26 17:10:29 +00001132 if max_buffer_size is not None:
1133 warnings.warn("max_buffer_size is deprecated", DeprecationWarning, 2)
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001134
1135 if not reader.readable():
1136 raise IOError('"reader" argument must be readable.')
1137
1138 if not writer.writable():
1139 raise IOError('"writer" argument must be writable.')
1140
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001141 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001142 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001143
1144 def read(self, n=None):
1145 if n is None:
1146 n = -1
1147 return self.reader.read(n)
1148
1149 def readinto(self, b):
1150 return self.reader.readinto(b)
1151
1152 def write(self, b):
1153 return self.writer.write(b)
1154
1155 def peek(self, n=0):
1156 return self.reader.peek(n)
1157
1158 def read1(self, n):
1159 return self.reader.read1(n)
1160
1161 def readable(self):
1162 return self.reader.readable()
1163
1164 def writable(self):
1165 return self.writer.writable()
1166
1167 def flush(self):
1168 return self.writer.flush()
1169
1170 def close(self):
1171 self.writer.close()
1172 self.reader.close()
1173
1174 def isatty(self):
1175 return self.reader.isatty() or self.writer.isatty()
1176
1177 @property
1178 def closed(self):
1179 return self.writer.closed
1180
1181
1182class BufferedRandom(BufferedWriter, BufferedReader):
1183
1184 """A buffered interface to random access streams.
1185
1186 The constructor creates a reader and writer for a seekable stream,
1187 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001188 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001189 """
1190
Benjamin Peterson59406a92009-03-26 17:10:29 +00001191 _warning_stack_offset = 3
1192
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001193 def __init__(self, raw,
1194 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1195 raw._checkSeekable()
1196 BufferedReader.__init__(self, raw, buffer_size)
1197 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1198
1199 def seek(self, pos, whence=0):
1200 if not (0 <= whence <= 2):
1201 raise ValueError("invalid whence")
1202 self.flush()
1203 if self._read_buf:
1204 # Undo read ahead.
1205 with self._read_lock:
1206 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1207 # First do the raw seek, then empty the read buffer, so that
1208 # if the raw seek fails, we don't lose buffered data forever.
1209 pos = self.raw.seek(pos, whence)
1210 with self._read_lock:
1211 self._reset_read_buf()
1212 if pos < 0:
1213 raise IOError("seek() returned invalid position")
1214 return pos
1215
1216 def tell(self):
1217 if self._write_buf:
1218 return BufferedWriter.tell(self)
1219 else:
1220 return BufferedReader.tell(self)
1221
1222 def truncate(self, pos=None):
1223 if pos is None:
1224 pos = self.tell()
1225 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001226 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001227
1228 def read(self, n=None):
1229 if n is None:
1230 n = -1
1231 self.flush()
1232 return BufferedReader.read(self, n)
1233
1234 def readinto(self, b):
1235 self.flush()
1236 return BufferedReader.readinto(self, b)
1237
1238 def peek(self, n=0):
1239 self.flush()
1240 return BufferedReader.peek(self, n)
1241
1242 def read1(self, n):
1243 self.flush()
1244 return BufferedReader.read1(self, n)
1245
1246 def write(self, b):
1247 if self._read_buf:
1248 # Undo readahead
1249 with self._read_lock:
1250 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1251 self._reset_read_buf()
1252 return BufferedWriter.write(self, b)
1253
1254
1255class TextIOBase(IOBase):
1256
1257 """Base class for text I/O.
1258
1259 This class provides a character and line based interface to stream
1260 I/O. There is no readinto method because Python's character strings
1261 are immutable. There is no public constructor.
1262 """
1263
1264 def read(self, n: int = -1) -> str:
1265 """Read at most n characters from stream.
1266
1267 Read from underlying buffer until we have n characters or we hit EOF.
1268 If n is negative or omitted, read until EOF.
1269 """
1270 self._unsupported("read")
1271
1272 def write(self, s: str) -> int:
1273 """Write string s to stream."""
1274 self._unsupported("write")
1275
1276 def truncate(self, pos: int = None) -> int:
1277 """Truncate size to pos."""
1278 self._unsupported("truncate")
1279
1280 def readline(self) -> str:
1281 """Read until newline or EOF.
1282
1283 Returns an empty string if EOF is hit immediately.
1284 """
1285 self._unsupported("readline")
1286
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001287 def detach(self) -> None:
1288 """
1289 Separate the underlying buffer from the TextIOBase and return it.
1290
1291 After the underlying buffer has been detached, the TextIO is in an
1292 unusable state.
1293 """
1294 self._unsupported("detach")
1295
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001296 @property
1297 def encoding(self):
1298 """Subclasses should override."""
1299 return None
1300
1301 @property
1302 def newlines(self):
1303 """Line endings translated so far.
1304
1305 Only line endings translated during reading are considered.
1306
1307 Subclasses should override.
1308 """
1309 return None
1310
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001311 @property
1312 def errors(self):
1313 """Error setting of the decoder or encoder.
1314
1315 Subclasses should override."""
1316 return None
1317
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001318io.TextIOBase.register(TextIOBase)
1319
1320
1321class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1322 r"""Codec used when reading a file in universal newlines mode. It wraps
1323 another incremental decoder, translating \r\n and \r into \n. It also
1324 records the types of newlines encountered. When used with
1325 translate=False, it ensures that the newline sequence is returned in
1326 one piece.
1327 """
1328 def __init__(self, decoder, translate, errors='strict'):
1329 codecs.IncrementalDecoder.__init__(self, errors=errors)
1330 self.translate = translate
1331 self.decoder = decoder
1332 self.seennl = 0
1333 self.pendingcr = False
1334
1335 def decode(self, input, final=False):
1336 # decode input (with the eventual \r from a previous pass)
1337 if self.decoder is None:
1338 output = input
1339 else:
1340 output = self.decoder.decode(input, final=final)
1341 if self.pendingcr and (output or final):
1342 output = "\r" + output
1343 self.pendingcr = False
1344
1345 # retain last \r even when not translating data:
1346 # then readline() is sure to get \r\n in one pass
1347 if output.endswith("\r") and not final:
1348 output = output[:-1]
1349 self.pendingcr = True
1350
1351 # Record which newlines are read
1352 crlf = output.count('\r\n')
1353 cr = output.count('\r') - crlf
1354 lf = output.count('\n') - crlf
1355 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1356 | (crlf and self._CRLF)
1357
1358 if self.translate:
1359 if crlf:
1360 output = output.replace("\r\n", "\n")
1361 if cr:
1362 output = output.replace("\r", "\n")
1363
1364 return output
1365
1366 def getstate(self):
1367 if self.decoder is None:
1368 buf = b""
1369 flag = 0
1370 else:
1371 buf, flag = self.decoder.getstate()
1372 flag <<= 1
1373 if self.pendingcr:
1374 flag |= 1
1375 return buf, flag
1376
1377 def setstate(self, state):
1378 buf, flag = state
1379 self.pendingcr = bool(flag & 1)
1380 if self.decoder is not None:
1381 self.decoder.setstate((buf, flag >> 1))
1382
1383 def reset(self):
1384 self.seennl = 0
1385 self.pendingcr = False
1386 if self.decoder is not None:
1387 self.decoder.reset()
1388
1389 _LF = 1
1390 _CR = 2
1391 _CRLF = 4
1392
1393 @property
1394 def newlines(self):
1395 return (None,
1396 "\n",
1397 "\r",
1398 ("\r", "\n"),
1399 "\r\n",
1400 ("\n", "\r\n"),
1401 ("\r", "\r\n"),
1402 ("\r", "\n", "\r\n")
1403 )[self.seennl]
1404
1405
1406class TextIOWrapper(TextIOBase):
1407
1408 r"""Character and line based layer over a BufferedIOBase object, buffer.
1409
1410 encoding gives the name of the encoding that the stream will be
1411 decoded or encoded with. It defaults to locale.getpreferredencoding.
1412
1413 errors determines the strictness of encoding and decoding (see the
1414 codecs.register) and defaults to "strict".
1415
1416 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1417 handling of line endings. If it is None, universal newlines is
1418 enabled. With this enabled, on input, the lines endings '\n', '\r',
1419 or '\r\n' are translated to '\n' before being returned to the
1420 caller. Conversely, on output, '\n' is translated to the system
1421 default line seperator, os.linesep. If newline is any other of its
1422 legal values, that newline becomes the newline when the file is read
1423 and it is returned untranslated. On output, '\n' is converted to the
1424 newline.
1425
1426 If line_buffering is True, a call to flush is implied when a call to
1427 write contains a newline character.
1428 """
1429
1430 _CHUNK_SIZE = 2048
1431
1432 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1433 line_buffering=False):
1434 if newline is not None and not isinstance(newline, str):
1435 raise TypeError("illegal newline type: %r" % (type(newline),))
1436 if newline not in (None, "", "\n", "\r", "\r\n"):
1437 raise ValueError("illegal newline value: %r" % (newline,))
1438 if encoding is None:
1439 try:
1440 encoding = os.device_encoding(buffer.fileno())
1441 except (AttributeError, UnsupportedOperation):
1442 pass
1443 if encoding is None:
1444 try:
1445 import locale
1446 except ImportError:
1447 # Importing locale may fail if Python is being built
1448 encoding = "ascii"
1449 else:
1450 encoding = locale.getpreferredencoding()
1451
1452 if not isinstance(encoding, str):
1453 raise ValueError("invalid encoding: %r" % encoding)
1454
1455 if errors is None:
1456 errors = "strict"
1457 else:
1458 if not isinstance(errors, str):
1459 raise ValueError("invalid errors: %r" % errors)
1460
1461 self.buffer = buffer
1462 self._line_buffering = line_buffering
1463 self._encoding = encoding
1464 self._errors = errors
1465 self._readuniversal = not newline
1466 self._readtranslate = newline is None
1467 self._readnl = newline
1468 self._writetranslate = newline != ''
1469 self._writenl = newline or os.linesep
1470 self._encoder = None
1471 self._decoder = None
1472 self._decoded_chars = '' # buffer for text returned from decoder
1473 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1474 self._snapshot = None # info for reconstructing decoder state
1475 self._seekable = self._telling = self.buffer.seekable()
1476
Antoine Pitroue4501852009-05-14 18:55:55 +00001477 if self._seekable and self.writable():
1478 position = self.buffer.tell()
1479 if position != 0:
1480 try:
1481 self._get_encoder().setstate(0)
1482 except LookupError:
1483 # Sometimes the encoder doesn't exist
1484 pass
1485
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001486 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1487 # where dec_flags is the second (integer) item of the decoder state
1488 # and next_input is the chunk of input bytes that comes next after the
1489 # snapshot point. We use this to reconstruct decoder states in tell().
1490
1491 # Naming convention:
1492 # - "bytes_..." for integer variables that count input bytes
1493 # - "chars_..." for integer variables that count decoded characters
1494
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001495 def __repr__(self):
Antoine Pitrou716c4442009-05-23 19:04:03 +00001496 try:
1497 name = self.name
1498 except AttributeError:
1499 return "<_pyio.TextIOWrapper encoding={0!r}>".format(self.encoding)
1500 else:
1501 return "<_pyio.TextIOWrapper name={0!r} encoding={1!r}>".format(
1502 name, self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001503
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001504 @property
1505 def encoding(self):
1506 return self._encoding
1507
1508 @property
1509 def errors(self):
1510 return self._errors
1511
1512 @property
1513 def line_buffering(self):
1514 return self._line_buffering
1515
1516 def seekable(self):
1517 return self._seekable
1518
1519 def readable(self):
1520 return self.buffer.readable()
1521
1522 def writable(self):
1523 return self.buffer.writable()
1524
1525 def flush(self):
1526 self.buffer.flush()
1527 self._telling = self._seekable
1528
1529 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00001530 if self.buffer is not None and not self.closed:
1531 self.flush()
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001532 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001533
1534 @property
1535 def closed(self):
1536 return self.buffer.closed
1537
1538 @property
1539 def name(self):
1540 return self.buffer.name
1541
1542 def fileno(self):
1543 return self.buffer.fileno()
1544
1545 def isatty(self):
1546 return self.buffer.isatty()
1547
1548 def write(self, s: str):
1549 if self.closed:
1550 raise ValueError("write to closed file")
1551 if not isinstance(s, str):
1552 raise TypeError("can't write %s to text stream" %
1553 s.__class__.__name__)
1554 length = len(s)
1555 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1556 if haslf and self._writetranslate and self._writenl != "\n":
1557 s = s.replace("\n", self._writenl)
1558 encoder = self._encoder or self._get_encoder()
1559 # XXX What if we were just reading?
1560 b = encoder.encode(s)
1561 self.buffer.write(b)
1562 if self._line_buffering and (haslf or "\r" in s):
1563 self.flush()
1564 self._snapshot = None
1565 if self._decoder:
1566 self._decoder.reset()
1567 return length
1568
1569 def _get_encoder(self):
1570 make_encoder = codecs.getincrementalencoder(self._encoding)
1571 self._encoder = make_encoder(self._errors)
1572 return self._encoder
1573
1574 def _get_decoder(self):
1575 make_decoder = codecs.getincrementaldecoder(self._encoding)
1576 decoder = make_decoder(self._errors)
1577 if self._readuniversal:
1578 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1579 self._decoder = decoder
1580 return decoder
1581
1582 # The following three methods implement an ADT for _decoded_chars.
1583 # Text returned from the decoder is buffered here until the client
1584 # requests it by calling our read() or readline() method.
1585 def _set_decoded_chars(self, chars):
1586 """Set the _decoded_chars buffer."""
1587 self._decoded_chars = chars
1588 self._decoded_chars_used = 0
1589
1590 def _get_decoded_chars(self, n=None):
1591 """Advance into the _decoded_chars buffer."""
1592 offset = self._decoded_chars_used
1593 if n is None:
1594 chars = self._decoded_chars[offset:]
1595 else:
1596 chars = self._decoded_chars[offset:offset + n]
1597 self._decoded_chars_used += len(chars)
1598 return chars
1599
1600 def _rewind_decoded_chars(self, n):
1601 """Rewind the _decoded_chars buffer."""
1602 if self._decoded_chars_used < n:
1603 raise AssertionError("rewind decoded_chars out of bounds")
1604 self._decoded_chars_used -= n
1605
1606 def _read_chunk(self):
1607 """
1608 Read and decode the next chunk of data from the BufferedReader.
1609 """
1610
1611 # The return value is True unless EOF was reached. The decoded
1612 # string is placed in self._decoded_chars (replacing its previous
1613 # value). The entire input chunk is sent to the decoder, though
1614 # some of it may remain buffered in the decoder, yet to be
1615 # converted.
1616
1617 if self._decoder is None:
1618 raise ValueError("no decoder")
1619
1620 if self._telling:
1621 # To prepare for tell(), we need to snapshot a point in the
1622 # file where the decoder's input buffer is empty.
1623
1624 dec_buffer, dec_flags = self._decoder.getstate()
1625 # Given this, we know there was a valid snapshot point
1626 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1627
1628 # Read a chunk, decode it, and put the result in self._decoded_chars.
1629 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1630 eof = not input_chunk
1631 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
1632
1633 if self._telling:
1634 # At the snapshot point, len(dec_buffer) bytes before the read,
1635 # the next input to be decoded is dec_buffer + input_chunk.
1636 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1637
1638 return not eof
1639
1640 def _pack_cookie(self, position, dec_flags=0,
1641 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1642 # The meaning of a tell() cookie is: seek to position, set the
1643 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1644 # into the decoder with need_eof as the EOF flag, then skip
1645 # chars_to_skip characters of the decoded result. For most simple
1646 # decoders, tell() will often just give a byte offset in the file.
1647 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1648 (chars_to_skip<<192) | bool(need_eof)<<256)
1649
1650 def _unpack_cookie(self, bigint):
1651 rest, position = divmod(bigint, 1<<64)
1652 rest, dec_flags = divmod(rest, 1<<64)
1653 rest, bytes_to_feed = divmod(rest, 1<<64)
1654 need_eof, chars_to_skip = divmod(rest, 1<<64)
1655 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1656
1657 def tell(self):
1658 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001659 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001660 if not self._telling:
1661 raise IOError("telling position disabled by next() call")
1662 self.flush()
1663 position = self.buffer.tell()
1664 decoder = self._decoder
1665 if decoder is None or self._snapshot is None:
1666 if self._decoded_chars:
1667 # This should never happen.
1668 raise AssertionError("pending decoded text")
1669 return position
1670
1671 # Skip backward to the snapshot point (see _read_chunk).
1672 dec_flags, next_input = self._snapshot
1673 position -= len(next_input)
1674
1675 # How many decoded characters have been used up since the snapshot?
1676 chars_to_skip = self._decoded_chars_used
1677 if chars_to_skip == 0:
1678 # We haven't moved from the snapshot point.
1679 return self._pack_cookie(position, dec_flags)
1680
1681 # Starting from the snapshot position, we will walk the decoder
1682 # forward until it gives us enough decoded characters.
1683 saved_state = decoder.getstate()
1684 try:
1685 # Note our initial start point.
1686 decoder.setstate((b'', dec_flags))
1687 start_pos = position
1688 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1689 need_eof = 0
1690
1691 # Feed the decoder one byte at a time. As we go, note the
1692 # nearest "safe start point" before the current location
1693 # (a point where the decoder has nothing buffered, so seek()
1694 # can safely start from there and advance to this location).
1695 next_byte = bytearray(1)
1696 for next_byte[0] in next_input:
1697 bytes_fed += 1
1698 chars_decoded += len(decoder.decode(next_byte))
1699 dec_buffer, dec_flags = decoder.getstate()
1700 if not dec_buffer and chars_decoded <= chars_to_skip:
1701 # Decoder buffer is empty, so this is a safe start point.
1702 start_pos += bytes_fed
1703 chars_to_skip -= chars_decoded
1704 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1705 if chars_decoded >= chars_to_skip:
1706 break
1707 else:
1708 # We didn't get enough decoded data; signal EOF to get more.
1709 chars_decoded += len(decoder.decode(b'', final=True))
1710 need_eof = 1
1711 if chars_decoded < chars_to_skip:
1712 raise IOError("can't reconstruct logical file position")
1713
1714 # The returned cookie corresponds to the last safe start point.
1715 return self._pack_cookie(
1716 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1717 finally:
1718 decoder.setstate(saved_state)
1719
1720 def truncate(self, pos=None):
1721 self.flush()
1722 if pos is None:
1723 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001724 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001725
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001726 def detach(self):
1727 if self.buffer is None:
1728 raise ValueError("buffer is already detached")
1729 self.flush()
1730 buffer = self.buffer
1731 self.buffer = None
1732 return buffer
1733
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001734 def seek(self, cookie, whence=0):
1735 if self.closed:
1736 raise ValueError("tell on closed file")
1737 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001738 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001739 if whence == 1: # seek relative to current position
1740 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001741 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001742 # Seeking to the current position should attempt to
1743 # sync the underlying buffer with the current position.
1744 whence = 0
1745 cookie = self.tell()
1746 if whence == 2: # seek relative to end of file
1747 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001748 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001749 self.flush()
1750 position = self.buffer.seek(0, 2)
1751 self._set_decoded_chars('')
1752 self._snapshot = None
1753 if self._decoder:
1754 self._decoder.reset()
1755 return position
1756 if whence != 0:
1757 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
1758 (whence,))
1759 if cookie < 0:
1760 raise ValueError("negative seek position %r" % (cookie,))
1761 self.flush()
1762
1763 # The strategy of seek() is to go back to the safe start point
1764 # and replay the effect of read(chars_to_skip) from there.
1765 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1766 self._unpack_cookie(cookie)
1767
1768 # Seek back to the safe start point.
1769 self.buffer.seek(start_pos)
1770 self._set_decoded_chars('')
1771 self._snapshot = None
1772
1773 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001774 if cookie == 0 and self._decoder:
1775 self._decoder.reset()
1776 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001777 self._decoder = self._decoder or self._get_decoder()
1778 self._decoder.setstate((b'', dec_flags))
1779 self._snapshot = (dec_flags, b'')
1780
1781 if chars_to_skip:
1782 # Just like _read_chunk, feed the decoder and save a snapshot.
1783 input_chunk = self.buffer.read(bytes_to_feed)
1784 self._set_decoded_chars(
1785 self._decoder.decode(input_chunk, need_eof))
1786 self._snapshot = (dec_flags, input_chunk)
1787
1788 # Skip chars_to_skip of the decoded characters.
1789 if len(self._decoded_chars) < chars_to_skip:
1790 raise IOError("can't restore logical file position")
1791 self._decoded_chars_used = chars_to_skip
1792
Antoine Pitroue4501852009-05-14 18:55:55 +00001793 # Finally, reset the encoder (merely useful for proper BOM handling)
1794 try:
1795 encoder = self._encoder or self._get_encoder()
1796 except LookupError:
1797 # Sometimes the encoder doesn't exist
1798 pass
1799 else:
1800 if cookie != 0:
1801 encoder.setstate(0)
1802 else:
1803 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001804 return cookie
1805
1806 def read(self, n=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00001807 self._checkReadable()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001808 if n is None:
1809 n = -1
1810 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00001811 try:
1812 n.__index__
1813 except AttributeError as err:
1814 raise TypeError("an integer is required") from err
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001815 if n < 0:
1816 # Read everything.
1817 result = (self._get_decoded_chars() +
1818 decoder.decode(self.buffer.read(), final=True))
1819 self._set_decoded_chars('')
1820 self._snapshot = None
1821 return result
1822 else:
1823 # Keep reading chunks until we have n characters to return.
1824 eof = False
1825 result = self._get_decoded_chars(n)
1826 while len(result) < n and not eof:
1827 eof = not self._read_chunk()
1828 result += self._get_decoded_chars(n - len(result))
1829 return result
1830
1831 def __next__(self):
1832 self._telling = False
1833 line = self.readline()
1834 if not line:
1835 self._snapshot = None
1836 self._telling = self._seekable
1837 raise StopIteration
1838 return line
1839
1840 def readline(self, limit=None):
1841 if self.closed:
1842 raise ValueError("read from closed file")
1843 if limit is None:
1844 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +00001845 elif not isinstance(limit, int):
1846 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001847
1848 # Grab all the decoded text (we will rewind any extra bits later).
1849 line = self._get_decoded_chars()
1850
1851 start = 0
1852 # Make the decoder if it doesn't already exist.
1853 if not self._decoder:
1854 self._get_decoder()
1855
1856 pos = endpos = None
1857 while True:
1858 if self._readtranslate:
1859 # Newlines are already translated, only search for \n
1860 pos = line.find('\n', start)
1861 if pos >= 0:
1862 endpos = pos + 1
1863 break
1864 else:
1865 start = len(line)
1866
1867 elif self._readuniversal:
1868 # Universal newline search. Find any of \r, \r\n, \n
1869 # The decoder ensures that \r\n are not split in two pieces
1870
1871 # In C we'd look for these in parallel of course.
1872 nlpos = line.find("\n", start)
1873 crpos = line.find("\r", start)
1874 if crpos == -1:
1875 if nlpos == -1:
1876 # Nothing found
1877 start = len(line)
1878 else:
1879 # Found \n
1880 endpos = nlpos + 1
1881 break
1882 elif nlpos == -1:
1883 # Found lone \r
1884 endpos = crpos + 1
1885 break
1886 elif nlpos < crpos:
1887 # Found \n
1888 endpos = nlpos + 1
1889 break
1890 elif nlpos == crpos + 1:
1891 # Found \r\n
1892 endpos = crpos + 2
1893 break
1894 else:
1895 # Found \r
1896 endpos = crpos + 1
1897 break
1898 else:
1899 # non-universal
1900 pos = line.find(self._readnl)
1901 if pos >= 0:
1902 endpos = pos + len(self._readnl)
1903 break
1904
1905 if limit >= 0 and len(line) >= limit:
1906 endpos = limit # reached length limit
1907 break
1908
1909 # No line ending seen yet - get more data'
1910 while self._read_chunk():
1911 if self._decoded_chars:
1912 break
1913 if self._decoded_chars:
1914 line += self._get_decoded_chars()
1915 else:
1916 # end of file
1917 self._set_decoded_chars('')
1918 self._snapshot = None
1919 return line
1920
1921 if limit >= 0 and endpos > limit:
1922 endpos = limit # don't exceed limit
1923
1924 # Rewind _decoded_chars to just after the line ending we found.
1925 self._rewind_decoded_chars(len(line) - endpos)
1926 return line[:endpos]
1927
1928 @property
1929 def newlines(self):
1930 return self._decoder.newlines if self._decoder else None
1931
1932
1933class StringIO(TextIOWrapper):
1934 """Text I/O implementation using an in-memory buffer.
1935
1936 The initial_value argument sets the value of object. The newline
1937 argument is like the one of TextIOWrapper's constructor.
1938 """
1939
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001940 def __init__(self, initial_value="", newline="\n"):
1941 super(StringIO, self).__init__(BytesIO(),
1942 encoding="utf-8",
1943 errors="strict",
1944 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00001945 # Issue #5645: make universal newlines semantics the same as in the
1946 # C version, even under Windows.
1947 if newline is None:
1948 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00001949 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001950 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00001951 raise TypeError("initial_value must be str or None, not {0}"
1952 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001953 initial_value = str(initial_value)
1954 self.write(initial_value)
1955 self.seek(0)
1956
1957 def getvalue(self):
1958 self.flush()
1959 return self.buffer.getvalue().decode(self._encoding, self._errors)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00001960
1961 def __repr__(self):
1962 # TextIOWrapper tells the encoding in its repr. In StringIO,
1963 # that's a implementation detail.
1964 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00001965
1966 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001967 def errors(self):
1968 return None
1969
1970 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00001971 def encoding(self):
1972 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001973
1974 def detach(self):
1975 # This doesn't make sense on StringIO.
1976 self._unsupported("detach")