Debian Codegraph @

lib-python/3/_pyio.py

raw symbols SCIP
1 """
2 Python implementation of the io module.
3 """
4
5 import os
6 import abc
7 import codecs
8 import errno
9 import stat
10 import sys
11 # Import _thread instead of threading to reduce startup cost
12 from _thread import allocate_lock as Lock
13 if sys.platform in {'win32', 'cygwin'}:
14 from msvcrt import setmode as _setmode
15 else:
16 _setmode = None
17
18 import io
19 from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
20
21 valid_seek_flags = {0, 1, 2} # Hardwired values
22 if hasattr(os, 'SEEK_HOLE') :
23 valid_seek_flags.add(os.SEEK_HOLE)
24 valid_seek_flags.add(os.SEEK_DATA)
25
26 # open() uses st_blksize whenever we can
27 DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
28
29 # NOTE: Base classes defined here are registered with the "official" ABCs
30 # defined in io.py. We don't use real inheritance though, because we don't want
31 # to inherit the C implementations.
32
33 # Rebind for compatibility
34 BlockingIOError = BlockingIOError
35
36 # Does io.IOBase finalizer log the exception if the close() method fails?
37 # The exception is ignored silently by default in release build.
38 _IOBASE_EMITS_UNRAISABLE = (hasattr(sys, "gettotalrefcount") or sys.flags.dev_mode)
39 # Does open() check its 'errors' argument?
40 _CHECK_ERRORS = _IOBASE_EMITS_UNRAISABLE
41
42
43 def text_encoding(encoding, stacklevel=2):
44 """
45 A helper function to choose the text encoding.
46
47 When encoding is not None, this function returns it.
48 Otherwise, this function returns the default text encoding
49 (i.e. "locale" or "utf-8" depends on UTF-8 mode).
50
51 This function emits an EncodingWarning if *encoding* is None and
52 sys.flags.warn_default_encoding is true.
53
54 This can be used in APIs with an encoding=None parameter
55 that pass it to TextIOWrapper or open.
56 However, please consider using encoding="utf-8" for new APIs.
57 """
58 if encoding is None:
59 if sys.flags.utf8_mode:
60 encoding = "utf-8"
61 else:
62 encoding = "locale"
63 if sys.flags.warn_default_encoding:
64 import warnings
65 warnings.warn("'encoding' argument not specified.",
66 EncodingWarning, stacklevel + 1)
67 return encoding
68
69
70 # Wrapper for builtins.open
71 #
72 # Trick so that open() won't become a bound method when stored
73 # as a class variable (as dbm.dumb does).
74 #
75 # See init_set_builtins_open() in Python/pylifecycle.c.
76 @staticmethod
77 def open(file, mode="r", buffering=-1, encoding=None, errors=None,
78 newline=None, closefd=True, opener=None):
79
80 r"""Open file and return a stream. Raise OSError upon failure.
81
82 file is either a text or byte string giving the name (and the path
83 if the file isn't in the current working directory) of the file to
84 be opened or an integer file descriptor of the file to be
85 wrapped. (If a file descriptor is given, it is closed when the
86 returned I/O object is closed, unless closefd is set to False.)
87
88 mode is an optional string that specifies the mode in which the file is
89 opened. It defaults to 'r' which means open for reading in text mode. Other
90 common values are 'w' for writing (truncating the file if it already
91 exists), 'x' for exclusive creation of a new file, and 'a' for appending
92 (which on some Unix systems, means that all writes append to the end of the
93 file regardless of the current seek position). In text mode, if encoding is
94 not specified the encoding used is platform dependent. (For reading and
95 writing raw bytes use binary mode and leave encoding unspecified.) The
96 available modes are:
97
98 ========= ===============================================================
99 Character Meaning
100 --------- ---------------------------------------------------------------
101 'r' open for reading (default)
102 'w' open for writing, truncating the file first
103 'x' create a new file and open it for writing
104 'a' open for writing, appending to the end of the file if it exists
105 'b' binary mode
106 't' text mode (default)
107 '+' open a disk file for updating (reading and writing)
108 ========= ===============================================================
109
110 The default mode is 'rt' (open for reading text). For binary random
111 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
112 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
113 raises an `FileExistsError` if the file already exists.
114
115 Python distinguishes between files opened in binary and text modes,
116 even when the underlying operating system doesn't. Files opened in
117 binary mode (appending 'b' to the mode argument) return contents as
118 bytes objects without any decoding. In text mode (the default, or when
119 't' is appended to the mode argument), the contents of the file are
120 returned as strings, the bytes having been first decoded using a
121 platform-dependent encoding or using the specified encoding if given.
122
123 buffering is an optional integer used to set the buffering policy.
124 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
125 line buffering (only usable in text mode), and an integer > 1 to indicate
126 the size of a fixed-size chunk buffer. When no buffering argument is
127 given, the default buffering policy works as follows:
128
129 * Binary files are buffered in fixed-size chunks; the size of the buffer
130 is chosen using a heuristic trying to determine the underlying device's
131 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
132 On many systems, the buffer will typically be 4096 or 8192 bytes long.
133
134 * "Interactive" text files (files for which isatty() returns True)
135 use line buffering. Other text files use the policy described above
136 for binary files.
137
138 encoding is the str name of the encoding used to decode or encode the
139 file. This should only be used in text mode. The default encoding is
140 platform dependent, but any encoding supported by Python can be
141 passed. See the codecs module for the list of supported encodings.
142
143 errors is an optional string that specifies how encoding errors are to
144 be handled---this argument should not be used in binary mode. Pass
145 'strict' to raise a ValueError exception if there is an encoding error
146 (the default of None has the same effect), or pass 'ignore' to ignore
147 errors. (Note that ignoring encoding errors can lead to data loss.)
148 See the documentation for codecs.register for a list of the permitted
149 encoding error strings.
150
151 newline is a string controlling how universal newlines works (it only
152 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
153 as follows:
154
155 * On input, if newline is None, universal newlines mode is
156 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
157 these are translated into '\n' before being returned to the
158 caller. If it is '', universal newline mode is enabled, but line
159 endings are returned to the caller untranslated. If it has any of
160 the other legal values, input lines are only terminated by the given
161 string, and the line ending is returned to the caller untranslated.
162
163 * On output, if newline is None, any '\n' characters written are
164 translated to the system default line separator, os.linesep. If
165 newline is '', no translation takes place. If newline is any of the
166 other legal values, any '\n' characters written are translated to
167 the given string.
168
169 closedfd is a bool. If closefd is False, the underlying file descriptor will
170 be kept open when the file is closed. This does not work when a file name is
171 given and must be True in that case.
172
173 The newly created file is non-inheritable.
174
175 A custom opener can be used by passing a callable as *opener*. The
176 underlying file descriptor for the file object is then obtained by calling
177 *opener* with (*file*, *flags*). *opener* must return an open file
178 descriptor (passing os.open as *opener* results in functionality similar to
179 passing None).
180
181 open() returns a file object whose type depends on the mode, and
182 through which the standard file operations such as reading and writing
183 are performed. When open() is used to open a file in a text mode ('w',
184 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
185 a file in a binary mode, the returned class varies: in read binary
186 mode, it returns a BufferedReader; in write binary and append binary
187 modes, it returns a BufferedWriter, and in read/write mode, it returns
188 a BufferedRandom.
189
190 It is also possible to use a string or bytearray as a file for both
191 reading and writing. For strings StringIO can be used like a file
192 opened in a text mode, and for bytes a BytesIO can be used like a file
193 opened in a binary mode.
194 """
195 if not isinstance(file, int):
196 file = os.fspath(file)
197 if not isinstance(file, (str, bytes, int)):
198 raise TypeError("invalid file: %r" % file)
199 if not isinstance(mode, str):
200 raise TypeError("invalid mode: %r" % mode)
201 if not isinstance(buffering, int):
202 raise TypeError("invalid buffering: %r" % buffering)
203 if encoding is not None and not isinstance(encoding, str):
204 raise TypeError("invalid encoding: %r" % encoding)
205 if errors is not None and not isinstance(errors, str):
206 raise TypeError("invalid errors: %r" % errors)
207 modes = set(mode)
208 if modes - set("axrwb+t") or len(mode) > len(modes):
209 raise ValueError("invalid mode: %r" % mode)
210 creating = "x" in modes
211 reading = "r" in modes
212 writing = "w" in modes
213 appending = "a" in modes
214 updating = "+" in modes
215 text = "t" in modes
216 binary = "b" in modes
217 if text and binary:
218 raise ValueError("can't have text and binary mode at once")
219 if creating + reading + writing + appending > 1:
220 raise ValueError("can't have read/write/append mode at once")
221 if not (creating or reading or writing or appending):
222 raise ValueError("must have exactly one of read/write/append mode")
223 if binary and encoding is not None:
224 raise ValueError("binary mode doesn't take an encoding argument")
225 if binary and errors is not None:
226 raise ValueError("binary mode doesn't take an errors argument")
227 if binary and newline is not None:
228 raise ValueError("binary mode doesn't take a newline argument")
229 if binary and buffering == 1:
230 import warnings
231 warnings.warn("line buffering (buffering=1) isn't supported in binary "
232 "mode, the default buffer size will be used",
233 RuntimeWarning, 2)
234 raw = FileIO(file,
235 (creating and "x" or "") +
236 (reading and "r" or "") +
237 (writing and "w" or "") +
238 (appending and "a" or "") +
239 (updating and "+" or ""),
240 closefd, opener=opener)
241 result = raw
242 try:
243 line_buffering = False
244 if buffering == 1 or buffering < 0 and raw.isatty():
245 buffering = -1
246 line_buffering = True
247 if buffering < 0:
248 buffering = DEFAULT_BUFFER_SIZE
249 try:
250 bs = os.fstat(raw.fileno()).st_blksize
251 except (OSError, AttributeError):
252 pass
253 else:
254 if bs > 1:
255 buffering = bs
256 if buffering < 0:
257 raise ValueError("invalid buffering size")
258 if buffering == 0:
259 if binary:
260 return result
261 raise ValueError("can't have unbuffered text I/O")
262 if updating:
263 buffer = BufferedRandom(raw, buffering)
264 elif creating or writing or appending:
265 buffer = BufferedWriter(raw, buffering)
266 elif reading:
267 buffer = BufferedReader(raw, buffering)
268 else:
269 raise ValueError("unknown mode: %r" % mode)
270 result = buffer
271 if binary:
272 return result
273 encoding = text_encoding(encoding)
274 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
275 result = text
276 text.mode = mode
277 return result
278 except:
279 result.close()
280 raise
281
282 # Define a default pure-Python implementation for open_code()
283 # that does not allow hooks. Warn on first use. Defined for tests.
284 def _open_code_with_warning(path):
285 """Opens the provided file with mode ``'rb'``. This function
286 should be used when the intent is to treat the contents as
287 executable code.
288
289 ``path`` should be an absolute path.
290
291 When supported by the runtime, this function can be hooked
292 in order to allow embedders more control over code files.
293 This functionality is not supported on the current runtime.
294 """
295 import warnings
296 warnings.warn("_pyio.open_code() may not be using hooks",
297 RuntimeWarning, 2)
298 return open(path, "rb")
299
300 try:
301 open_code = io.open_code
302 except AttributeError:
303 open_code = _open_code_with_warning
304
305
306 def __getattr__(name):
307 if name == "OpenWrapper":
308 # bpo-43680: Until Python 3.9, _pyio.open was not a static method and
309 # builtins.open was set to OpenWrapper to not become a bound method
310 # when set to a class variable. _io.open is a built-in function whereas
311 # _pyio.open is a Python function. In Python 3.10, _pyio.open() is now
312 # a static method, and builtins.open() is now io.open().
313 import warnings
314 warnings.warn('OpenWrapper is deprecated, use open instead',
315 DeprecationWarning, stacklevel=2)
316 global OpenWrapper
317 OpenWrapper = open
318 return OpenWrapper
319 raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
320
321
322 # In normal operation, both `UnsupportedOperation`s should be bound to the
323 # same object.
324 try:
325 UnsupportedOperation = io.UnsupportedOperation
326 except AttributeError:
327 class UnsupportedOperation(OSError, ValueError):
328 pass
329
330
331 class IOBase(metaclass=abc.ABCMeta):
332
333 """The abstract base class for all I/O classes.
334
335 This class provides dummy implementations for many methods that
336 derived classes can override selectively; the default implementations
337 represent a file that cannot be read, written or seeked.
338
339 Even though IOBase does not declare read or write because
340 their signatures will vary, implementations and clients should
341 consider those methods part of the interface. Also, implementations
342 may raise UnsupportedOperation when operations they do not support are
343 called.
344
345 The basic type used for binary data read from or written to a file is
346 bytes. Other bytes-like objects are accepted as method arguments too.
347 Text I/O classes work with str data.
348
349 Note that calling any method (even inquiries) on a closed stream is
350 undefined. Implementations may raise OSError in this case.
351
352 IOBase (and its subclasses) support the iterator protocol, meaning
353 that an IOBase object can be iterated over yielding the lines in a
354 stream.
355
356 IOBase also supports the :keyword:`with` statement. In this example,
357 fp is closed after the suite of the with statement is complete:
358
359 with open('spam.txt', 'r') as fp:
360 fp.write('Spam and eggs!')
361 """
362
363 ### Internal ###
364
365 def _unsupported(self, name):
366 """Internal: raise an OSError exception for unsupported operations."""
367 raise UnsupportedOperation("%s.%s() not supported" %
368 (self.__class__.__name__, name))
369
370 ### Positioning ###
371
372 def seek(self, pos, whence=0):
373 """Change stream position.
374
375 Change the stream position to byte offset pos. Argument pos is
376 interpreted relative to the position indicated by whence. Values
377 for whence are ints:
378
379 * 0 -- start of stream (the default); offset should be zero or positive
380 * 1 -- current stream position; offset may be negative
381 * 2 -- end of stream; offset is usually negative
382 Some operating systems / file systems could provide additional values.
383
384 Return an int indicating the new absolute position.
385 """
386 self._unsupported("seek")
387
388 def tell(self):
389 """Return an int indicating the current stream position."""
390 return self.seek(0, 1)
391
392 def truncate(self, pos=None):
393 """Truncate file to size bytes.
394
395 Size defaults to the current IO position as reported by tell(). Return
396 the new size.
397 """
398 self._unsupported("truncate")
399
400 ### Flush and close ###
401
402 def flush(self):
403 """Flush write buffers, if applicable.
404
405 This is not implemented for read-only and non-blocking streams.
406 """
407 self._checkClosed()
408 # XXX Should this return the number of bytes written???
409
410 __closed = False
411
412 def close(self):
413 """Flush and close the IO object.
414
415 This method has no effect if the file is already closed.
416 """
417 if not self.__closed:
418 try:
419 self.flush()
420 finally:
421 self.__closed = True
422
423 def __del__(self):
424 """Destructor. Calls close()."""
425 try:
426 closed = self.closed
427 except AttributeError:
428 # If getting closed fails, then the object is probably
429 # in an unusable state, so ignore.
430 return
431
432 if closed:
433 return
434
435 if _IOBASE_EMITS_UNRAISABLE:
436 self.close()
437 else:
438 # The try/except block is in case this is called at program
439 # exit time, when it's possible that globals have already been
440 # deleted, and then the close() call might fail. Since
441 # there's nothing we can do about such failures and they annoy
442 # the end users, we suppress the traceback.
443 try:
444 self.close()
445 except:
446 pass
447
448 ### Inquiries ###
449
450 def seekable(self):
451 """Return a bool indicating whether object supports random access.
452
453 If False, seek(), tell() and truncate() will raise OSError.
454 This method may need to do a test seek().
455 """
456 return False
457
458 def _checkSeekable(self, msg=None):
459 """Internal: raise UnsupportedOperation if file is not seekable
460 """
461 if not self.seekable():
462 raise UnsupportedOperation("File or stream is not seekable."
463 if msg is None else msg)
464
465 def readable(self):
466 """Return a bool indicating whether object was opened for reading.
467
468 If False, read() will raise OSError.
469 """
470 return False
471
472 def _checkReadable(self, msg=None):
473 """Internal: raise UnsupportedOperation if file is not readable
474 """
475 if not self.readable():
476 raise UnsupportedOperation("File or stream is not readable."
477 if msg is None else msg)
478
479 def writable(self):
480 """Return a bool indicating whether object was opened for writing.
481
482 If False, write() and truncate() will raise OSError.
483 """
484 return False
485
486 def _checkWritable(self, msg=None):
487 """Internal: raise UnsupportedOperation if file is not writable
488 """
489 if not self.writable():
490 raise UnsupportedOperation("File or stream is not writable."
491 if msg is None else msg)
492
493 @property
494 def closed(self):
495 """closed: bool. True iff the file has been closed.
496
497 For backwards compatibility, this is a property, not a predicate.
498 """
499 return self.__closed
500
501 def _checkClosed(self, msg=None):
502 """Internal: raise a ValueError if file is closed
503 """
504 if self.closed:
505 raise ValueError("I/O operation on closed file."
506 if msg is None else msg)
507
508 ### Context manager ###
509
510 def __enter__(self): # That's a forward reference
511 """Context management protocol. Returns self (an instance of IOBase)."""
512 self._checkClosed()
513 return self
514
515 def __exit__(self, *args):
516 """Context management protocol. Calls close()"""
517 self.close()
518
519 ### Lower-level APIs ###
520
521 # XXX Should these be present even if unimplemented?
522
523 def fileno(self):
524 """Returns underlying file descriptor (an int) if one exists.
525
526 An OSError is raised if the IO object does not use a file descriptor.
527 """
528 self._unsupported("fileno")
529
530 def isatty(self):
531 """Return a bool indicating whether this is an 'interactive' stream.
532
533 Return False if it can't be determined.
534 """
535 self._checkClosed()
536 return False
537
538 ### Readline[s] and writelines ###
539
540 def readline(self, size=-1):
541 r"""Read and return a line of bytes from the stream.
542
543 If size is specified, at most size bytes will be read.
544 Size should be an int.
545
546 The line terminator is always b'\n' for binary files; for text
547 files, the newlines argument to open can be used to select the line
548 terminator(s) recognized.
549 """
550 # For backwards compatibility, a (slowish) readline().
551 if hasattr(self, "peek"):
552 def nreadahead():
553 readahead = self.peek(1)
554 if not readahead:
555 return 1
556 n = (readahead.find(b"\n") + 1) or len(readahead)
557 if size >= 0:
558 n = min(n, size)
559 return n
560 else:
561 def nreadahead():
562 return 1
563 if size is None:
564 size = -1
565 else:
566 try:
567 size_index = size.__index__
568 except AttributeError:
569 raise TypeError(f"{size!r} is not an integer")
570 else:
571 size = size_index()
572 res = bytearray()
573 while size < 0 or len(res) < size:
574 b = self.read(nreadahead())
575 if not b:
576 break
577 res += b
578 if res.endswith(b"\n"):
579 break
580 return bytes(res)
581
582 def __iter__(self):
583 self._checkClosed()
584 return self
585
586 def __next__(self):
587 line = self.readline()
588 if not line:
589 raise StopIteration
590 return line
591
592 def readlines(self, hint=None):
593 """Return a list of lines from the stream.
594
595 hint can be specified to control the number of lines read: no more
596 lines will be read if the total size (in bytes/characters) of all
597 lines so far exceeds hint.
598 """
599 if hint is None or hint <= 0:
600 return list(self)
601 n = 0
602 lines = []
603 for line in self:
604 lines.append(line)
605 n += len(line)
606 if n >= hint:
607 break
608 return lines
609
610 def writelines(self, lines):
611 """Write a list of lines to the stream.
612
613 Line separators are not added, so it is usual for each of the lines
614 provided to have a line separator at the end.
615 """
616 self._checkClosed()
617 for line in lines:
618 self.write(line)
619
620 io.IOBase.register(IOBase)
621
622
623 class RawIOBase(IOBase):
624
625 """Base class for raw binary I/O."""
626
627 # The read() method is implemented by calling readinto(); derived
628 # classes that want to support read() only need to implement
629 # readinto() as a primitive operation. In general, readinto() can be
630 # more efficient than read().
631
632 # (It would be tempting to also provide an implementation of
633 # readinto() in terms of read(), in case the latter is a more suitable
634 # primitive operation, but that would lead to nasty recursion in case
635 # a subclass doesn't implement either.)
636
637 def read(self, size=-1):
638 """Read and return up to size bytes, where size is an int.
639
640 Returns an empty bytes object on EOF, or None if the object is
641 set not to block and has no data to read.
642 """
643 if size is None:
644 size = -1
645 if size < 0:
646 return self.readall()
647 b = bytearray(size.__index__())
648 n = self.readinto(b)
649 if n is None:
650 return None
651 del b[n:]
652 return bytes(b)
653
654 def readall(self):
655 """Read until EOF, using multiple read() call."""
656 res = bytearray()
657 while True:
658 data = self.read(DEFAULT_BUFFER_SIZE)
659 if not data:
660 break
661 res += data
662 if res:
663 return bytes(res)
664 else:
665 # b'' or None
666 return data
667
668 def readinto(self, b):
669 """Read bytes into a pre-allocated bytes-like object b.
670
671 Returns an int representing the number of bytes read (0 for EOF), or
672 None if the object is set not to block and has no data to read.
673 """
674 self._unsupported("readinto")
675
676 def write(self, b):
677 """Write the given buffer to the IO stream.
678
679 Returns the number of bytes written, which may be less than the
680 length of b in bytes.
681 """
682 self._unsupported("write")
683
684 io.RawIOBase.register(RawIOBase)
685 from _io import FileIO
686 RawIOBase.register(FileIO)
687
688
689 class BufferedIOBase(IOBase):
690
691 """Base class for buffered IO objects.
692
693 The main difference with RawIOBase is that the read() method
694 supports omitting the size argument, and does not have a default
695 implementation that defers to readinto().
696
697 In addition, read(), readinto() and write() may raise
698 BlockingIOError if the underlying raw stream is in non-blocking
699 mode and not ready; unlike their raw counterparts, they will never
700 return None.
701
702 A typical implementation should not inherit from a RawIOBase
703 implementation, but wrap one.
704 """
705
706 def read(self, size=-1):
707 """Read and return up to size bytes, where size is an int.
708
709 If the argument is omitted, None, or negative, reads and
710 returns all data until EOF.
711
712 If the argument is positive, and the underlying raw stream is
713 not 'interactive', multiple raw reads may be issued to satisfy
714 the byte count (unless EOF is reached first). But for
715 interactive raw streams (XXX and for pipes?), at most one raw
716 read will be issued, and a short result does not imply that
717 EOF is imminent.
718
719 Returns an empty bytes array on EOF.
720
721 Raises BlockingIOError if the underlying raw stream has no
722 data at the moment.
723 """
724 self._unsupported("read")
725
726 def read1(self, size=-1):
727 """Read up to size bytes with at most one read() system call,
728 where size is an int.
729 """
730 self._unsupported("read1")
731
732 def readinto(self, b):
733 """Read bytes into a pre-allocated bytes-like object b.
734
735 Like read(), this may issue multiple reads to the underlying raw
736 stream, unless the latter is 'interactive'.
737
738 Returns an int representing the number of bytes read (0 for EOF).
739
740 Raises BlockingIOError if the underlying raw stream has no
741 data at the moment.
742 """
743
744 return self._readinto(b, read1=False)
745
746 def readinto1(self, b):
747 """Read bytes into buffer *b*, using at most one system call
748
749 Returns an int representing the number of bytes read (0 for EOF).
750
751 Raises BlockingIOError if the underlying raw stream has no
752 data at the moment.
753 """
754
755 return self._readinto(b, read1=True)
756
757 def _readinto(self, b, read1):
758 if not isinstance(b, memoryview):
759 b = memoryview(b)
760 b = b.cast('B')
761
762 if read1:
763 data = self.read1(len(b))
764 else:
765 data = self.read(len(b))
766 n = len(data)
767
768 b[:n] = data
769
770 return n
771
772 def write(self, b):
773 """Write the given bytes buffer to the IO stream.
774
775 Return the number of bytes written, which is always the length of b
776 in bytes.
777
778 Raises BlockingIOError if the buffer is full and the
779 underlying raw stream cannot accept more data at the moment.
780 """
781 self._unsupported("write")
782
783 def detach(self):
784 """
785 Separate the underlying raw stream from the buffer and return it.
786
787 After the raw stream has been detached, the buffer is in an unusable
788 state.
789 """
790 self._unsupported("detach")
791
792 io.BufferedIOBase.register(BufferedIOBase)
793
794
795 class _BufferedIOMixin(BufferedIOBase):
796
797 """A mixin implementation of BufferedIOBase with an underlying raw stream.
798
799 This passes most requests on to the underlying raw stream. It
800 does *not* provide implementations of read(), readinto() or
801 write().
802 """
803
804 def __init__(self, raw):
805 self._raw = raw
806
807 ### Positioning ###
808
809 def seek(self, pos, whence=0):
810 new_position = self.raw.seek(pos, whence)
811 if new_position < 0:
812 raise OSError("seek() returned an invalid position")
813 return new_position
814
815 def tell(self):
816 pos = self.raw.tell()
817 if pos < 0:
818 raise OSError("tell() returned an invalid position")
819 return pos
820
821 def truncate(self, pos=None):
822 self._checkClosed()
823 self._checkWritable()
824
825 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
826 # and a flush may be necessary to synch both views of the current
827 # file state.
828 self.flush()
829
830 if pos is None:
831 pos = self.tell()
832 # XXX: Should seek() be used, instead of passing the position
833 # XXX directly to truncate?
834 return self.raw.truncate(pos)
835
836 ### Flush and close ###
837
838 def flush(self):
839 if self.closed:
840 raise ValueError("flush on closed file")
841 self.raw.flush()
842
843 def close(self):
844 if self.raw is not None and not self.closed:
845 try:
846 # may raise BlockingIOError or BrokenPipeError etc
847 self.flush()
848 finally:
849 self.raw.close()
850
851 def detach(self):
852 if self.raw is None:
853 raise ValueError("raw stream already detached")
854 self.flush()
855 raw = self._raw
856 self._raw = None
857 return raw
858
859 ### Inquiries ###
860
861 def seekable(self):
862 return self.raw.seekable()
863
864 @property
865 def raw(self):
866 return self._raw
867
868 @property
869 def closed(self):
870 return self.raw.closed
871
872 @property
873 def name(self):
874 return self.raw.name
875
876 @property
877 def mode(self):
878 return self.raw.mode
879
880 def __getstate__(self):
881 raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
882
883 def __repr__(self):
884 modname = self.__class__.__module__
885 clsname = self.__class__.__qualname__
886 try:
887 name = self.name
888 except AttributeError:
889 return "<{}.{}>".format(modname, clsname)
890 else:
891 return "<{}.{} name={!r}>".format(modname, clsname, name)
892
893 ### Lower-level APIs ###
894
895 def fileno(self):
896 return self.raw.fileno()
897
898 def isatty(self):
899 return self.raw.isatty()
900
901
902 class BytesIO(BufferedIOBase):
903
904 """Buffered I/O implementation using an in-memory bytes buffer."""
905
906 # Initialize _buffer as soon as possible since it's used by __del__()
907 # which calls close()
908 _buffer = None
909
910 def __init__(self, initial_bytes=None):
911 buf = bytearray()
912 if initial_bytes is not None:
913 buf += initial_bytes
914 self._buffer = buf
915 self._pos = 0
916
917 def __getstate__(self):
918 if self.closed:
919 raise ValueError("__getstate__ on closed file")
920 return self.__dict__.copy()
921
922 def getvalue(self):
923 """Return the bytes value (contents) of the buffer
924 """
925 if self.closed:
926 raise ValueError("getvalue on closed file")
927 return bytes(self._buffer)
928
929 def getbuffer(self):
930 """Return a readable and writable view of the buffer.
931 """
932 if self.closed:
933 raise ValueError("getbuffer on closed file")
934 return memoryview(self._buffer)
935
936 def close(self):
937 if self._buffer is not None:
938 self._buffer.clear()
939 super().close()
940
941 def read(self, size=-1):
942 if self.closed:
943 raise ValueError("read from closed file")
944 if size is None:
945 size = -1
946 else:
947 try:
948 size_index = size.__index__
949 except AttributeError:
950 raise TypeError(f"{size!r} is not an integer")
951 else:
952 size = size_index()
953 if size < 0:
954 size = len(self._buffer)
955 if len(self._buffer) <= self._pos:
956 return b""
957 newpos = min(len(self._buffer), self._pos + size)
958 b = self._buffer[self._pos : newpos]
959 self._pos = newpos
960 return bytes(b)
961
962 def read1(self, size=-1):
963 """This is the same as read.
964 """
965 return self.read(size)
966
967 def write(self, b):
968 if self.closed:
969 raise ValueError("write to closed file")
970 if isinstance(b, str):
971 raise TypeError("can't write str to binary stream")
972 with memoryview(b) as view:
973 n = view.nbytes # Size of any bytes-like object
974 if n == 0:
975 return 0
976 pos = self._pos
977 if pos > len(self._buffer):
978 # Inserts null bytes between the current end of the file
979 # and the new write position.
980 padding = b'\x00' * (pos - len(self._buffer))
981 self._buffer += padding
982 self._buffer[pos:pos + n] = b
983 self._pos += n
984 return n
985
986 def seek(self, pos, whence=0):
987 if self.closed:
988 raise ValueError("seek on closed file")
989 try:
990 pos_index = pos.__index__
991 except AttributeError:
992 raise TypeError(f"{pos!r} is not an integer")
993 else:
994 pos = pos_index()
995 if whence == 0:
996 if pos < 0:
997 raise ValueError("negative seek position %r" % (pos,))
998 self._pos = pos
999 elif whence == 1:
1000 self._pos = max(0, self._pos + pos)
1001 elif whence == 2:
1002 self._pos = max(0, len(self._buffer) + pos)
1003 else:
1004 raise ValueError("unsupported whence value")
1005 return self._pos
1006
1007 def tell(self):
1008 if self.closed:
1009 raise ValueError("tell on closed file")
1010 return self._pos
1011
1012 def truncate(self, pos=None):
1013 if self.closed:
1014 raise ValueError("truncate on closed file")
1015 if pos is None:
1016 pos = self._pos
1017 else:
1018 try:
1019 pos_index = pos.__index__
1020 except AttributeError:
1021 raise TypeError(f"{pos!r} is not an integer")
1022 else:
1023 pos = pos_index()
1024 if pos < 0:
1025 raise ValueError("negative truncate position %r" % (pos,))
1026 del self._buffer[pos:]
1027 return pos
1028
1029 def readable(self):
1030 if self.closed:
1031 raise ValueError("I/O operation on closed file.")
1032 return True
1033
1034 def writable(self):
1035 if self.closed:
1036 raise ValueError("I/O operation on closed file.")
1037 return True
1038
1039 def seekable(self):
1040 if self.closed:
1041 raise ValueError("I/O operation on closed file.")
1042 return True
1043
1044
1045 class BufferedReader(_BufferedIOMixin):
1046
1047 """BufferedReader(raw[, buffer_size])
1048
1049 A buffer for a readable, sequential BaseRawIO object.
1050
1051 The constructor creates a BufferedReader for the given readable raw
1052 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
1053 is used.
1054 """
1055
1056 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
1057 """Create a new buffered reader using the given readable raw IO object.
1058 """
1059 if not raw.readable():
1060 raise OSError('"raw" argument must be readable.')
1061
1062 _BufferedIOMixin.__init__(self, raw)
1063 if buffer_size <= 0:
1064 raise ValueError("invalid buffer size")
1065 self.buffer_size = buffer_size
1066 self._reset_read_buf()
1067 self._read_lock = Lock()
1068
1069 def readable(self):
1070 return self.raw.readable()
1071
1072 def _reset_read_buf(self):
1073 self._read_buf = b""
1074 self._read_pos = 0
1075
1076 def read(self, size=None):
1077 """Read size bytes.
1078
1079 Returns exactly size bytes of data unless the underlying raw IO
1080 stream reaches EOF or if the call would block in non-blocking
1081 mode. If size is negative, read until EOF or until read() would
1082 block.
1083 """
1084 if size is not None and size < -1:
1085 raise ValueError("invalid number of bytes to read")
1086 with self._read_lock:
1087 return self._read_unlocked(size)
1088
1089 def _read_unlocked(self, n=None):
1090 nodata_val = b""
1091 empty_values = (b"", None)
1092 buf = self._read_buf
1093 pos = self._read_pos
1094
1095 # Special case for when the number of bytes to read is unspecified.
1096 if n is None or n == -1:
1097 self._reset_read_buf()
1098 if hasattr(self.raw, 'readall'):
1099 chunk = self.raw.readall()
1100 if chunk is None:
1101 return buf[pos:] or None
1102 else:
1103 return buf[pos:] + chunk
1104 chunks = [buf[pos:]] # Strip the consumed bytes.
1105 current_size = 0
1106 while True:
1107 # Read until EOF or until read() would block.
1108 chunk = self.raw.read()
1109 if chunk in empty_values:
1110 nodata_val = chunk
1111 break
1112 current_size += len(chunk)
1113 chunks.append(chunk)
1114 return b"".join(chunks) or nodata_val
1115
1116 # The number of bytes to read is specified, return at most n bytes.
1117 avail = len(buf) - pos # Length of the available buffered data.
1118 if n <= avail:
1119 # Fast path: the data to read is fully buffered.
1120 self._read_pos += n
1121 return buf[pos:pos+n]
1122 # Slow path: read from the stream until enough bytes are read,
1123 # or until an EOF occurs or until read() would block.
1124 chunks = [buf[pos:]]
1125 wanted = max(self.buffer_size, n)
1126 while avail < n:
1127 chunk = self.raw.read(wanted)
1128 if chunk in empty_values:
1129 nodata_val = chunk
1130 break
1131 avail += len(chunk)
1132 chunks.append(chunk)
1133 # n is more than avail only when an EOF occurred or when
1134 # read() would have blocked.
1135 n = min(n, avail)
1136 out = b"".join(chunks)
1137 self._read_buf = out[n:] # Save the extra data in the buffer.
1138 self._read_pos = 0
1139 return out[:n] if out else nodata_val
1140
1141 def peek(self, size=0):
1142 """Returns buffered bytes without advancing the position.
1143
1144 The argument indicates a desired minimal number of bytes; we
1145 do at most one raw read to satisfy it. We never return more
1146 than self.buffer_size.
1147 """
1148 with self._read_lock:
1149 return self._peek_unlocked(size)
1150
1151 def _peek_unlocked(self, n=0):
1152 want = min(n, self.buffer_size)
1153 have = len(self._read_buf) - self._read_pos
1154 if have < want or have <= 0:
1155 to_read = self.buffer_size - have
1156 current = self.raw.read(to_read)
1157 if current:
1158 self._read_buf = self._read_buf[self._read_pos:] + current
1159 self._read_pos = 0
1160 return self._read_buf[self._read_pos:]
1161
1162 def read1(self, size=-1):
1163 """Reads up to size bytes, with at most one read() system call."""
1164 # Returns up to size bytes. If at least one byte is buffered, we
1165 # only return buffered bytes. Otherwise, we do one raw read.
1166 if size < 0:
1167 size = self.buffer_size
1168 if size == 0:
1169 return b""
1170 with self._read_lock:
1171 self._peek_unlocked(1)
1172 return self._read_unlocked(
1173 min(size, len(self._read_buf) - self._read_pos))
1174
1175 # Implementing readinto() and readinto1() is not strictly necessary (we
1176 # could rely on the base class that provides an implementation in terms of
1177 # read() and read1()). We do it anyway to keep the _pyio implementation
1178 # similar to the io implementation (which implements the methods for
1179 # performance reasons).
1180 def _readinto(self, buf, read1):
1181 """Read data into *buf* with at most one system call."""
1182
1183 # Need to create a memoryview object of type 'b', otherwise
1184 # we may not be able to assign bytes to it, and slicing it
1185 # would create a new object.
1186 if not isinstance(buf, memoryview):
1187 buf = memoryview(buf)
1188 if buf.nbytes == 0:
1189 return 0
1190 buf = buf.cast('B')
1191
1192 written = 0
1193 with self._read_lock:
1194 while written < len(buf):
1195
1196 # First try to read from internal buffer
1197 avail = min(len(self._read_buf) - self._read_pos, len(buf))
1198 if avail:
1199 buf[written:written+avail] = \
1200 self._read_buf[self._read_pos:self._read_pos+avail]
1201 self._read_pos += avail
1202 written += avail
1203 if written == len(buf):
1204 break
1205
1206 # If remaining space in callers buffer is larger than
1207 # internal buffer, read directly into callers buffer
1208 if len(buf) - written > self.buffer_size:
1209 n = self.raw.readinto(buf[written:])
1210 if not n:
1211 break # eof
1212 written += n
1213
1214 # Otherwise refill internal buffer - unless we're
1215 # in read1 mode and already got some data
1216 elif not (read1 and written):
1217 if not self._peek_unlocked(1):
1218 break # eof
1219
1220 # In readinto1 mode, return as soon as we have some data
1221 if read1 and written:
1222 break
1223
1224 return written
1225
1226 def tell(self):
1227 # GH-95782: Keep return value non-negative
1228 return max(_BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos, 0)
1229
1230 def seek(self, pos, whence=0):
1231 if whence not in valid_seek_flags:
1232 raise ValueError("invalid whence value")
1233 with self._read_lock:
1234 if whence == 1:
1235 pos -= len(self._read_buf) - self._read_pos
1236 pos = _BufferedIOMixin.seek(self, pos, whence)
1237 self._reset_read_buf()
1238 return pos
1239
1240 class BufferedWriter(_BufferedIOMixin):
1241
1242 """A buffer for a writeable sequential RawIO object.
1243
1244 The constructor creates a BufferedWriter for the given writeable raw
1245 stream. If the buffer_size is not given, it defaults to
1246 DEFAULT_BUFFER_SIZE.
1247 """
1248
1249 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
1250 if not raw.writable():
1251 raise OSError('"raw" argument must be writable.')
1252
1253 _BufferedIOMixin.__init__(self, raw)
1254 if buffer_size <= 0:
1255 raise ValueError("invalid buffer size")
1256 self.buffer_size = buffer_size
1257 self._write_buf = bytearray()
1258 self._write_lock = Lock()
1259
1260 def writable(self):
1261 return self.raw.writable()
1262
1263 def write(self, b):
1264 if isinstance(b, str):
1265 raise TypeError("can't write str to binary stream")
1266 with self._write_lock:
1267 if self.closed:
1268 raise ValueError("write to closed file")
1269 # XXX we can implement some more tricks to try and avoid
1270 # partial writes
1271 if len(self._write_buf) > self.buffer_size:
1272 # We're full, so let's pre-flush the buffer. (This may
1273 # raise BlockingIOError with characters_written == 0.)
1274 self._flush_unlocked()
1275 before = len(self._write_buf)
1276 self._write_buf.extend(b)
1277 written = len(self._write_buf) - before
1278 if len(self._write_buf) > self.buffer_size:
1279 try:
1280 self._flush_unlocked()
1281 except BlockingIOError as e:
1282 if len(self._write_buf) > self.buffer_size:
1283 # We've hit the buffer_size. We have to accept a partial
1284 # write and cut back our buffer.
1285 overage = len(self._write_buf) - self.buffer_size
1286 written -= overage
1287 self._write_buf = self._write_buf[:self.buffer_size]
1288 raise BlockingIOError(e.errno, e.strerror, written)
1289 return written
1290
1291 def truncate(self, pos=None):
1292 with self._write_lock:
1293 self._flush_unlocked()
1294 if pos is None:
1295 pos = self.raw.tell()
1296 return self.raw.truncate(pos)
1297
1298 def flush(self):
1299 with self._write_lock:
1300 self._flush_unlocked()
1301
1302 def _flush_unlocked(self):
1303 if self.closed:
1304 raise ValueError("flush on closed file")
1305 while self._write_buf:
1306 try:
1307 n = self.raw.write(self._write_buf)
1308 except BlockingIOError:
1309 raise RuntimeError("self.raw should implement RawIOBase: it "
1310 "should not raise BlockingIOError")
1311 if n is None:
1312 raise BlockingIOError(
1313 errno.EAGAIN,
1314 "write could not complete without blocking", 0)
1315 if n > len(self._write_buf) or n < 0:
1316 raise OSError("write() returned incorrect number of bytes")
1317 del self._write_buf[:n]
1318
1319 def tell(self):
1320 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1321
1322 def seek(self, pos, whence=0):
1323 if whence not in valid_seek_flags:
1324 raise ValueError("invalid whence value")
1325 with self._write_lock:
1326 self._flush_unlocked()
1327 return _BufferedIOMixin.seek(self, pos, whence)
1328
1329 def close(self):
1330 with self._write_lock:
1331 if self.raw is None or self.closed:
1332 return
1333 # We have to release the lock and call self.flush() (which will
1334 # probably just re-take the lock) in case flush has been overridden in
1335 # a subclass or the user set self.flush to something. This is the same
1336 # behavior as the C implementation.
1337 try:
1338 # may raise BlockingIOError or BrokenPipeError etc
1339 self.flush()
1340 finally:
1341 with self._write_lock:
1342 self.raw.close()
1343
1344
1345 class BufferedRWPair(BufferedIOBase):
1346
1347 """A buffered reader and writer object together.
1348
1349 A buffered reader object and buffered writer object put together to
1350 form a sequential IO object that can read and write. This is typically
1351 used with a socket or two-way pipe.
1352
1353 reader and writer are RawIOBase objects that are readable and
1354 writeable respectively. If the buffer_size is omitted it defaults to
1355 DEFAULT_BUFFER_SIZE.
1356 """
1357
1358 # XXX The usefulness of this (compared to having two separate IO
1359 # objects) is questionable.
1360
1361 def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
1362 """Constructor.
1363
1364 The arguments are two RawIO instances.
1365 """
1366 if not reader.readable():
1367 raise OSError('"reader" argument must be readable.')
1368
1369 if not writer.writable():
1370 raise OSError('"writer" argument must be writable.')
1371
1372 self.reader = BufferedReader(reader, buffer_size)
1373 self.writer = BufferedWriter(writer, buffer_size)
1374
1375 def read(self, size=-1):
1376 if size is None:
1377 size = -1
1378 return self.reader.read(size)
1379
1380 def readinto(self, b):
1381 return self.reader.readinto(b)
1382
1383 def write(self, b):
1384 return self.writer.write(b)
1385
1386 def peek(self, size=0):
1387 return self.reader.peek(size)
1388
1389 def read1(self, size=-1):
1390 return self.reader.read1(size)
1391
1392 def readinto1(self, b):
1393 return self.reader.readinto1(b)
1394
1395 def readable(self):
1396 return self.reader.readable()
1397
1398 def writable(self):
1399 return self.writer.writable()
1400
1401 def flush(self):
1402 return self.writer.flush()
1403
1404 def close(self):
1405 try:
1406 self.writer.close()
1407 finally:
1408 self.reader.close()
1409
1410 def isatty(self):
1411 return self.reader.isatty() or self.writer.isatty()
1412
1413 @property
1414 def closed(self):
1415 return self.writer.closed
1416
1417
1418 class BufferedRandom(BufferedWriter, BufferedReader):
1419
1420 """A buffered interface to random access streams.
1421
1422 The constructor creates a reader and writer for a seekable stream,
1423 raw, given in the first argument. If the buffer_size is omitted it
1424 defaults to DEFAULT_BUFFER_SIZE.
1425 """
1426
1427 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
1428 raw._checkSeekable()
1429 BufferedReader.__init__(self, raw, buffer_size)
1430 BufferedWriter.__init__(self, raw, buffer_size)
1431
1432 def seek(self, pos, whence=0):
1433 if whence not in valid_seek_flags:
1434 raise ValueError("invalid whence value")
1435 self.flush()
1436 if self._read_buf:
1437 # Undo read ahead.
1438 with self._read_lock:
1439 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1440 # First do the raw seek, then empty the read buffer, so that
1441 # if the raw seek fails, we don't lose buffered data forever.
1442 pos = self.raw.seek(pos, whence)
1443 with self._read_lock:
1444 self._reset_read_buf()
1445 if pos < 0:
1446 raise OSError("seek() returned invalid position")
1447 return pos
1448
1449 def tell(self):
1450 if self._write_buf:
1451 return BufferedWriter.tell(self)
1452 else:
1453 return BufferedReader.tell(self)
1454
1455 def truncate(self, pos=None):
1456 if pos is None:
1457 pos = self.tell()
1458 # Use seek to flush the read buffer.
1459 return BufferedWriter.truncate(self, pos)
1460
1461 def read(self, size=None):
1462 if size is None:
1463 size = -1
1464 self.flush()
1465 return BufferedReader.read(self, size)
1466
1467 def readinto(self, b):
1468 self.flush()
1469 return BufferedReader.readinto(self, b)
1470
1471 def peek(self, size=0):
1472 self.flush()
1473 return BufferedReader.peek(self, size)
1474
1475 def read1(self, size=-1):
1476 self.flush()
1477 return BufferedReader.read1(self, size)
1478
1479 def readinto1(self, b):
1480 self.flush()
1481 return BufferedReader.readinto1(self, b)
1482
1483 def write(self, b):
1484 if self._read_buf:
1485 # Undo readahead
1486 with self._read_lock:
1487 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1488 self._reset_read_buf()
1489 return BufferedWriter.write(self, b)
1490
1491
1492 class FileIO(RawIOBase):
1493 _fd = -1
1494 _created = False
1495 _readable = False
1496 _writable = False
1497 _appending = False
1498 _seekable = None
1499 _closefd = True
1500
1501 def __init__(self, file, mode='r', closefd=True, opener=None):
1502 """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
1503 writing, exclusive creation or appending. The file will be created if it
1504 doesn't exist when opened for writing or appending; it will be truncated
1505 when opened for writing. A FileExistsError will be raised if it already
1506 exists when opened for creating. Opening a file for creating implies
1507 writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode
1508 to allow simultaneous reading and writing. A custom opener can be used by
1509 passing a callable as *opener*. The underlying file descriptor for the file
1510 object is then obtained by calling opener with (*name*, *flags*).
1511 *opener* must return an open file descriptor (passing os.open as *opener*
1512 results in functionality similar to passing None).
1513 """
1514 if self._fd >= 0:
1515 # Have to close the existing file first.
1516 try:
1517 if self._closefd:
1518 os.close(self._fd)
1519 finally:
1520 self._fd = -1
1521
1522 if isinstance(file, float):
1523 raise TypeError('integer argument expected, got float')
1524 if isinstance(file, int):
1525 fd = file
1526 if fd < 0:
1527 raise ValueError('negative file descriptor')
1528 else:
1529 fd = -1
1530
1531 if not isinstance(mode, str):
1532 raise TypeError('invalid mode: %s' % (mode,))
1533 if not set(mode) <= set('xrwab+'):
1534 raise ValueError('invalid mode: %s' % (mode,))
1535 if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1:
1536 raise ValueError('Must have exactly one of create/read/write/append '
1537 'mode and at most one plus')
1538
1539 if 'x' in mode:
1540 self._created = True
1541 self._writable = True
1542 flags = os.O_EXCL | os.O_CREAT
1543 elif 'r' in mode:
1544 self._readable = True
1545 flags = 0
1546 elif 'w' in mode:
1547 self._writable = True
1548 flags = os.O_CREAT | os.O_TRUNC
1549 elif 'a' in mode:
1550 self._writable = True
1551 self._appending = True
1552 flags = os.O_APPEND | os.O_CREAT
1553
1554 if '+' in mode:
1555 self._readable = True
1556 self._writable = True
1557
1558 if self._readable and self._writable:
1559 flags |= os.O_RDWR
1560 elif self._readable:
1561 flags |= os.O_RDONLY
1562 else:
1563 flags |= os.O_WRONLY
1564
1565 flags |= getattr(os, 'O_BINARY', 0)
1566
1567 noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or
1568 getattr(os, 'O_CLOEXEC', 0))
1569 flags |= noinherit_flag
1570
1571 owned_fd = None
1572 try:
1573 if fd < 0:
1574 if not closefd:
1575 raise ValueError('Cannot use closefd=False with file name')
1576 if opener is None:
1577 fd = os.open(file, flags, 0o666)
1578 else:
1579 fd = opener(file, flags)
1580 if not isinstance(fd, int):
1581 raise TypeError('expected integer from opener')
1582 if fd < 0:
1583 raise OSError('Negative file descriptor')
1584 owned_fd = fd
1585 if not noinherit_flag:
1586 os.set_inheritable(fd, False)
1587
1588 self._closefd = closefd
1589 fdfstat = os.fstat(fd)
1590 try:
1591 if stat.S_ISDIR(fdfstat.st_mode):
1592 raise IsADirectoryError(errno.EISDIR,
1593 os.strerror(errno.EISDIR), file)
1594 except AttributeError:
1595 # Ignore the AttributeError if stat.S_ISDIR or errno.EISDIR
1596 # don't exist.
1597 pass
1598 self._blksize = getattr(fdfstat, 'st_blksize', 0)
1599 if self._blksize <= 1:
1600 self._blksize = DEFAULT_BUFFER_SIZE
1601
1602 if _setmode:
1603 # don't translate newlines (\r\n <=> \n)
1604 _setmode(fd, os.O_BINARY)
1605
1606 self.name = file
1607 if self._appending:
1608 # For consistent behaviour, we explicitly seek to the
1609 # end of file (otherwise, it might be done only on the
1610 # first write()).
1611 try:
1612 os.lseek(fd, 0, SEEK_END)
1613 except OSError as e:
1614 if e.errno != errno.ESPIPE:
1615 raise
1616 except:
1617 if owned_fd is not None:
1618 os.close(owned_fd)
1619 raise
1620 self._fd = fd
1621
1622 def __del__(self):
1623 if self._fd >= 0 and self._closefd and not self.closed:
1624 import warnings
1625 warnings.warn('unclosed file %r' % (self,), ResourceWarning,
1626 stacklevel=2, source=self)
1627 self.close()
1628
1629 def __getstate__(self):
1630 raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
1631
1632 def __repr__(self):
1633 class_name = '%s.%s' % (self.__class__.__module__,
1634 self.__class__.__qualname__)
1635 if self.closed:
1636 return '<%s [closed]>' % class_name
1637 try:
1638 name = self.name
1639 except AttributeError:
1640 return ('<%s fd=%d mode=%r closefd=%r>' %
1641 (class_name, self._fd, self.mode, self._closefd))
1642 else:
1643 return ('<%s name=%r mode=%r closefd=%r>' %
1644 (class_name, name, self.mode, self._closefd))
1645
1646 def _checkReadable(self):
1647 if not self._readable:
1648 raise UnsupportedOperation('File not open for reading')
1649
1650 def _checkWritable(self, msg=None):
1651 if not self._writable:
1652 raise UnsupportedOperation('File not open for writing')
1653
1654 def read(self, size=None):
1655 """Read at most size bytes, returned as bytes.
1656
1657 Only makes one system call, so less data may be returned than requested
1658 In non-blocking mode, returns None if no data is available.
1659 Return an empty bytes object at EOF.
1660 """
1661 self._checkClosed()
1662 self._checkReadable()
1663 if size is None or size < 0:
1664 return self.readall()
1665 try:
1666 return os.read(self._fd, size)
1667 except BlockingIOError:
1668 return None
1669
1670 def readall(self):
1671 """Read all data from the file, returned as bytes.
1672
1673 In non-blocking mode, returns as much as is immediately available,
1674 or None if no data is available. Return an empty bytes object at EOF.
1675 """
1676 self._checkClosed()
1677 self._checkReadable()
1678 bufsize = DEFAULT_BUFFER_SIZE
1679 try:
1680 pos = os.lseek(self._fd, 0, SEEK_CUR)
1681 end = os.fstat(self._fd).st_size
1682 if end >= pos:
1683 bufsize = end - pos + 1
1684 except OSError:
1685 pass
1686
1687 result = bytearray()
1688 while True:
1689 if len(result) >= bufsize:
1690 bufsize = len(result)
1691 bufsize += max(bufsize, DEFAULT_BUFFER_SIZE)
1692 n = bufsize - len(result)
1693 try:
1694 chunk = os.read(self._fd, n)
1695 except BlockingIOError:
1696 if result:
1697 break
1698 return None
1699 if not chunk: # reached the end of the file
1700 break
1701 result += chunk
1702
1703 return bytes(result)
1704
1705 def readinto(self, b):
1706 """Same as RawIOBase.readinto()."""
1707 m = memoryview(b).cast('B')
1708 data = self.read(len(m))
1709 n = len(data)
1710 m[:n] = data
1711 return n
1712
1713 def write(self, b):
1714 """Write bytes b to file, return number written.
1715
1716 Only makes one system call, so not all of the data may be written.
1717 The number of bytes actually written is returned. In non-blocking mode,
1718 returns None if the write would block.
1719 """
1720 self._checkClosed()
1721 self._checkWritable()
1722 try:
1723 return os.write(self._fd, b)
1724 except BlockingIOError:
1725 return None
1726
1727 def seek(self, pos, whence=SEEK_SET):
1728 """Move to new file position.
1729
1730 Argument offset is a byte count. Optional argument whence defaults to
1731 SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
1732 are SEEK_CUR or 1 (move relative to current position, positive or negative),
1733 and SEEK_END or 2 (move relative to end of file, usually negative, although
1734 many platforms allow seeking beyond the end of a file).
1735
1736 Note that not all file objects are seekable.
1737 """
1738 if isinstance(pos, float):
1739 raise TypeError('an integer is required')
1740 self._checkClosed()
1741 return os.lseek(self._fd, pos, whence)
1742
1743 def tell(self):
1744 """tell() -> int. Current file position.
1745
1746 Can raise OSError for non seekable files."""
1747 self._checkClosed()
1748 return os.lseek(self._fd, 0, SEEK_CUR)
1749
1750 def truncate(self, size=None):
1751 """Truncate the file to at most size bytes.
1752
1753 Size defaults to the current file position, as returned by tell().
1754 The current file position is changed to the value of size.
1755 """
1756 self._checkClosed()
1757 self._checkWritable()
1758 if size is None:
1759 size = self.tell()
1760 os.ftruncate(self._fd, size)
1761 return size
1762
1763 def close(self):
1764 """Close the file.
1765
1766 A closed file cannot be used for further I/O operations. close() may be
1767 called more than once without error.
1768 """
1769 if not self.closed:
1770 try:
1771 if self._closefd:
1772 os.close(self._fd)
1773 finally:
1774 super().close()
1775
1776 def seekable(self):
1777 """True if file supports random-access."""
1778 self._checkClosed()
1779 if self._seekable is None:
1780 try:
1781 self.tell()
1782 except OSError:
1783 self._seekable = False
1784 else:
1785 self._seekable = True
1786 return self._seekable
1787
1788 def readable(self):
1789 """True if file was opened in a read mode."""
1790 self._checkClosed()
1791 return self._readable
1792
1793 def writable(self):
1794 """True if file was opened in a write mode."""
1795 self._checkClosed()
1796 return self._writable
1797
1798 def fileno(self):
1799 """Return the underlying file descriptor (an integer)."""
1800 self._checkClosed()
1801 return self._fd
1802
1803 def isatty(self):
1804 """True if the file is connected to a TTY device."""
1805 self._checkClosed()
1806 return os.isatty(self._fd)
1807
1808 @property
1809 def closefd(self):
1810 """True if the file descriptor will be closed by close()."""
1811 return self._closefd
1812
1813 @property
1814 def mode(self):
1815 """String giving the file mode"""
1816 if self._created:
1817 if self._readable:
1818 return 'xb+'
1819 else:
1820 return 'xb'
1821 elif self._appending:
1822 if self._readable:
1823 return 'ab+'
1824 else:
1825 return 'ab'
1826 elif self._readable:
1827 if self._writable:
1828 return 'rb+'
1829 else:
1830 return 'rb'
1831 else:
1832 return 'wb'
1833
1834
1835 class TextIOBase(IOBase):
1836
1837 """Base class for text I/O.
1838
1839 This class provides a character and line based interface to stream
1840 I/O.
1841 """
1842
1843 def read(self, size=-1):
1844 """Read at most size characters from stream, where size is an int.
1845
1846 Read from underlying buffer until we have size characters or we hit EOF.
1847 If size is negative or omitted, read until EOF.
1848
1849 Returns a string.
1850 """
1851 self._unsupported("read")
1852
1853 def write(self, s):
1854 """Write string s to stream and returning an int."""
1855 self._unsupported("write")
1856
1857 def truncate(self, pos=None):
1858 """Truncate size to pos, where pos is an int."""
1859 self._unsupported("truncate")
1860
1861 def readline(self):
1862 """Read until newline or EOF.
1863
1864 Returns an empty string if EOF is hit immediately.
1865 """
1866 self._unsupported("readline")
1867
1868 def detach(self):
1869 """
1870 Separate the underlying buffer from the TextIOBase and return it.
1871
1872 After the underlying buffer has been detached, the TextIO is in an
1873 unusable state.
1874 """
1875 self._unsupported("detach")
1876
1877 @property
1878 def encoding(self):
1879 """Subclasses should override."""
1880 return None
1881
1882 @property
1883 def newlines(self):
1884 """Line endings translated so far.
1885
1886 Only line endings translated during reading are considered.
1887
1888 Subclasses should override.
1889 """
1890 return None
1891
1892 @property
1893 def errors(self):
1894 """Error setting of the decoder or encoder.
1895
1896 Subclasses should override."""
1897 return None
1898
1899 io.TextIOBase.register(TextIOBase)
1900
1901
1902 class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1903 r"""Codec used when reading a file in universal newlines mode. It wraps
1904 another incremental decoder, translating \r\n and \r into \n. It also
1905 records the types of newlines encountered. When used with
1906 translate=False, it ensures that the newline sequence is returned in
1907 one piece.
1908 """
1909 def __init__(self, decoder, translate, errors='strict'):
1910 codecs.IncrementalDecoder.__init__(self, errors=errors)
1911 self.translate = translate
1912 self.decoder = decoder
1913 self.seennl = 0
1914 self.pendingcr = False
1915
1916 def decode(self, input, final=False):
1917 # decode input (with the eventual \r from a previous pass)
1918 if self.decoder is None:
1919 output = input
1920 else:
1921 output = self.decoder.decode(input, final=final)
1922 if self.pendingcr and (output or final):
1923 output = "\r" + output
1924 self.pendingcr = False
1925
1926 # retain last \r even when not translating data:
1927 # then readline() is sure to get \r\n in one pass
1928 if output.endswith("\r") and not final:
1929 output = output[:-1]
1930 self.pendingcr = True
1931
1932 # Record which newlines are read
1933 crlf = output.count('\r\n')
1934 cr = output.count('\r') - crlf
1935 lf = output.count('\n') - crlf
1936 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1937 | (crlf and self._CRLF)
1938
1939 if self.translate:
1940 if crlf:
1941 output = output.replace("\r\n", "\n")
1942 if cr:
1943 output = output.replace("\r", "\n")
1944
1945 return output
1946
1947 def getstate(self):
1948 if self.decoder is None:
1949 buf = b""
1950 flag = 0
1951 else:
1952 buf, flag = self.decoder.getstate()
1953 flag <<= 1
1954 if self.pendingcr:
1955 flag |= 1
1956 return buf, flag
1957
1958 def setstate(self, state):
1959 buf, flag = state
1960 self.pendingcr = bool(flag & 1)
1961 if self.decoder is not None:
1962 self.decoder.setstate((buf, flag >> 1))
1963
1964 def reset(self):
1965 self.seennl = 0
1966 self.pendingcr = False
1967 if self.decoder is not None:
1968 self.decoder.reset()
1969
1970 _LF = 1
1971 _CR = 2
1972 _CRLF = 4
1973
1974 @property
1975 def newlines(self):
1976 return (None,
1977 "\n",
1978 "\r",
1979 ("\r", "\n"),
1980 "\r\n",
1981 ("\n", "\r\n"),
1982 ("\r", "\r\n"),
1983 ("\r", "\n", "\r\n")
1984 )[self.seennl]
1985
1986
1987 class TextIOWrapper(TextIOBase):
1988
1989 r"""Character and line based layer over a BufferedIOBase object, buffer.
1990
1991 encoding gives the name of the encoding that the stream will be
1992 decoded or encoded with. It defaults to locale.getencoding().
1993
1994 errors determines the strictness of encoding and decoding (see the
1995 codecs.register) and defaults to "strict".
1996
1997 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1998 handling of line endings. If it is None, universal newlines is
1999 enabled. With this enabled, on input, the lines endings '\n', '\r',
2000 or '\r\n' are translated to '\n' before being returned to the
2001 caller. Conversely, on output, '\n' is translated to the system
2002 default line separator, os.linesep. If newline is any other of its
2003 legal values, that newline becomes the newline when the file is read
2004 and it is returned untranslated. On output, '\n' is converted to the
2005 newline.
2006
2007 If line_buffering is True, a call to flush is implied when a call to
2008 write contains a newline character.
2009 """
2010
2011 _CHUNK_SIZE = 2048
2012
2013 # Initialize _buffer as soon as possible since it's used by __del__()
2014 # which calls close()
2015 _buffer = None
2016
2017 # The write_through argument has no effect here since this
2018 # implementation always writes through. The argument is present only
2019 # so that the signature can match the signature of the C version.
2020 def __init__(self, buffer, encoding=None, errors=None, newline=None,
2021 line_buffering=False, write_through=False):
2022 self._check_newline(newline)
2023 encoding = text_encoding(encoding)
2024
2025 if encoding == "locale":
2026 encoding = self._get_locale_encoding()
2027
2028 if not isinstance(encoding, str):
2029 raise ValueError("invalid encoding: %r" % encoding)
2030
2031 if not codecs.lookup(encoding)._is_text_encoding:
2032 msg = ("%r is not a text encoding; "
2033 "use codecs.open() to handle arbitrary codecs")
2034 raise LookupError(msg % encoding)
2035
2036 if errors is None:
2037 errors = "strict"
2038 else:
2039 if not isinstance(errors, str):
2040 raise ValueError("invalid errors: %r" % errors)
2041 if _CHECK_ERRORS:
2042 codecs.lookup_error(errors)
2043
2044 self._buffer = buffer
2045 self._decoded_chars = '' # buffer for text returned from decoder
2046 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
2047 self._snapshot = None # info for reconstructing decoder state
2048 self._seekable = self._telling = self.buffer.seekable()
2049 self._has_read1 = hasattr(self.buffer, 'read1')
2050 self._configure(encoding, errors, newline,
2051 line_buffering, write_through)
2052
2053 def _check_newline(self, newline):
2054 if newline is not None and not isinstance(newline, str):
2055 raise TypeError("illegal newline type: %r" % (type(newline),))
2056 if newline not in (None, "", "\n", "\r", "\r\n"):
2057 raise ValueError("illegal newline value: %r" % (newline,))
2058
2059 def _configure(self, encoding=None, errors=None, newline=None,
2060 line_buffering=False, write_through=False):
2061 self._encoding = encoding
2062 self._errors = errors
2063 self._encoder = None
2064 self._decoder = None
2065 self._b2cratio = 0.0
2066
2067 self._readuniversal = not newline
2068 self._readtranslate = newline is None
2069 self._readnl = newline
2070 self._writetranslate = newline != ''
2071 self._writenl = newline or os.linesep
2072
2073 self._line_buffering = line_buffering
2074 self._write_through = write_through
2075
2076 # don't write a BOM in the middle of a file
2077 if self._seekable and self.writable():
2078 position = self.buffer.tell()
2079 if position != 0:
2080 try:
2081 self._get_encoder().setstate(0)
2082 except LookupError:
2083 # Sometimes the encoder doesn't exist
2084 pass
2085
2086 # self._snapshot is either None, or a tuple (dec_flags, next_input)
2087 # where dec_flags is the second (integer) item of the decoder state
2088 # and next_input is the chunk of input bytes that comes next after the
2089 # snapshot point. We use this to reconstruct decoder states in tell().
2090
2091 # Naming convention:
2092 # - "bytes_..." for integer variables that count input bytes
2093 # - "chars_..." for integer variables that count decoded characters
2094
2095 def __repr__(self):
2096 result = "<{}.{}".format(self.__class__.__module__,
2097 self.__class__.__qualname__)
2098 try:
2099 name = self.name
2100 except AttributeError:
2101 pass
2102 else:
2103 result += " name={0!r}".format(name)
2104 try:
2105 mode = self.mode
2106 except AttributeError:
2107 pass
2108 else:
2109 result += " mode={0!r}".format(mode)
2110 return result + " encoding={0!r}>".format(self.encoding)
2111
2112 @property
2113 def encoding(self):
2114 return self._encoding
2115
2116 @property
2117 def errors(self):
2118 return self._errors
2119
2120 @property
2121 def line_buffering(self):
2122 return self._line_buffering
2123
2124 @property
2125 def write_through(self):
2126 return self._write_through
2127
2128 @property
2129 def buffer(self):
2130 return self._buffer
2131
2132 def reconfigure(self, *,
2133 encoding=None, errors=None, newline=Ellipsis,
2134 line_buffering=None, write_through=None):
2135 """Reconfigure the text stream with new parameters.
2136
2137 This also flushes the stream.
2138 """
2139 if (self._decoder is not None
2140 and (encoding is not None or errors is not None
2141 or newline is not Ellipsis)):
2142 raise UnsupportedOperation(
2143 "It is not possible to set the encoding or newline of stream "
2144 "after the first read")
2145
2146 if errors is None:
2147 if encoding is None:
2148 errors = self._errors
2149 else:
2150 errors = 'strict'
2151 elif not isinstance(errors, str):
2152 raise TypeError("invalid errors: %r" % errors)
2153
2154 if encoding is None:
2155 encoding = self._encoding
2156 else:
2157 if not isinstance(encoding, str):
2158 raise TypeError("invalid encoding: %r" % encoding)
2159 if encoding == "locale":
2160 encoding = self._get_locale_encoding()
2161
2162 if newline is Ellipsis:
2163 newline = self._readnl
2164 self._check_newline(newline)
2165
2166 if line_buffering is None:
2167 line_buffering = self.line_buffering
2168 if write_through is None:
2169 write_through = self.write_through
2170
2171 self.flush()
2172 self._configure(encoding, errors, newline,
2173 line_buffering, write_through)
2174
2175 def seekable(self):
2176 if self.closed:
2177 raise ValueError("I/O operation on closed file.")
2178 return self._seekable
2179
2180 def readable(self):
2181 return self.buffer.readable()
2182
2183 def writable(self):
2184 return self.buffer.writable()
2185
2186 def flush(self):
2187 self.buffer.flush()
2188 self._telling = self._seekable
2189
2190 def close(self):
2191 if self.buffer is not None and not self.closed:
2192 try:
2193 self.flush()
2194 finally:
2195 self.buffer.close()
2196
2197 @property
2198 def closed(self):
2199 return self.buffer.closed
2200
2201 @property
2202 def name(self):
2203 return self.buffer.name
2204
2205 def fileno(self):
2206 return self.buffer.fileno()
2207
2208 def isatty(self):
2209 return self.buffer.isatty()
2210
2211 def write(self, s):
2212 'Write data, where s is a str'
2213 if self.closed:
2214 raise ValueError("write to closed file")
2215 if not isinstance(s, str):
2216 raise TypeError("can't write %s to text stream" %
2217 s.__class__.__name__)
2218 length = len(s)
2219 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
2220 if haslf and self._writetranslate and self._writenl != "\n":
2221 s = s.replace("\n", self._writenl)
2222 encoder = self._encoder or self._get_encoder()
2223 # XXX What if we were just reading?
2224 b = encoder.encode(s)
2225 self.buffer.write(b)
2226 if self._line_buffering and (haslf or "\r" in s):
2227 self.flush()
2228 if self._snapshot is not None:
2229 self._set_decoded_chars('')
2230 self._snapshot = None
2231 if self._decoder:
2232 self._decoder.reset()
2233 return length
2234
2235 def _get_encoder(self):
2236 make_encoder = codecs.getincrementalencoder(self._encoding)
2237 self._encoder = make_encoder(self._errors)
2238 return self._encoder
2239
2240 def _get_decoder(self):
2241 make_decoder = codecs.getincrementaldecoder(self._encoding)
2242 decoder = make_decoder(self._errors)
2243 if self._readuniversal:
2244 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
2245 self._decoder = decoder
2246 return decoder
2247
2248 # The following three methods implement an ADT for _decoded_chars.
2249 # Text returned from the decoder is buffered here until the client
2250 # requests it by calling our read() or readline() method.
2251 def _set_decoded_chars(self, chars):
2252 """Set the _decoded_chars buffer."""
2253 self._decoded_chars = chars
2254 self._decoded_chars_used = 0
2255
2256 def _get_decoded_chars(self, n=None):
2257 """Advance into the _decoded_chars buffer."""
2258 offset = self._decoded_chars_used
2259 if n is None:
2260 chars = self._decoded_chars[offset:]
2261 else:
2262 chars = self._decoded_chars[offset:offset + n]
2263 self._decoded_chars_used += len(chars)
2264 return chars
2265
2266 def _get_locale_encoding(self):
2267 try:
2268 import locale
2269 except ImportError:
2270 # Importing locale may fail if Python is being built
2271 return "utf-8"
2272 else:
2273 return locale.getencoding()
2274
2275 def _rewind_decoded_chars(self, n):
2276 """Rewind the _decoded_chars buffer."""
2277 if self._decoded_chars_used < n:
2278 raise AssertionError("rewind decoded_chars out of bounds")
2279 self._decoded_chars_used -= n
2280
2281 def _read_chunk(self):
2282 """
2283 Read and decode the next chunk of data from the BufferedReader.
2284 """
2285
2286 # The return value is True unless EOF was reached. The decoded
2287 # string is placed in self._decoded_chars (replacing its previous
2288 # value). The entire input chunk is sent to the decoder, though
2289 # some of it may remain buffered in the decoder, yet to be
2290 # converted.
2291
2292 if self._decoder is None:
2293 raise ValueError("no decoder")
2294
2295 if self._telling:
2296 # To prepare for tell(), we need to snapshot a point in the
2297 # file where the decoder's input buffer is empty.
2298
2299 dec_buffer, dec_flags = self._decoder.getstate()
2300 # Given this, we know there was a valid snapshot point
2301 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
2302
2303 # Read a chunk, decode it, and put the result in self._decoded_chars.
2304 if self._has_read1:
2305 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
2306 else:
2307 input_chunk = self.buffer.read(self._CHUNK_SIZE)
2308 eof = not input_chunk
2309 decoded_chars = self._decoder.decode(input_chunk, eof)
2310 self._set_decoded_chars(decoded_chars)
2311 if decoded_chars:
2312 self._b2cratio = len(input_chunk) / len(self._decoded_chars)
2313 else:
2314 self._b2cratio = 0.0
2315
2316 if self._telling:
2317 # At the snapshot point, len(dec_buffer) bytes before the read,
2318 # the next input to be decoded is dec_buffer + input_chunk.
2319 self._snapshot = (dec_flags, dec_buffer + input_chunk)
2320
2321 return not eof
2322
2323 def _pack_cookie(self, position, dec_flags=0,
2324 bytes_to_feed=0, need_eof=False, chars_to_skip=0):
2325 # The meaning of a tell() cookie is: seek to position, set the
2326 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
2327 # into the decoder with need_eof as the EOF flag, then skip
2328 # chars_to_skip characters of the decoded result. For most simple
2329 # decoders, tell() will often just give a byte offset in the file.
2330 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
2331 (chars_to_skip<<192) | bool(need_eof)<<256)
2332
2333 def _unpack_cookie(self, bigint):
2334 rest, position = divmod(bigint, 1<<64)
2335 rest, dec_flags = divmod(rest, 1<<64)
2336 rest, bytes_to_feed = divmod(rest, 1<<64)
2337 need_eof, chars_to_skip = divmod(rest, 1<<64)
2338 return position, dec_flags, bytes_to_feed, bool(need_eof), chars_to_skip
2339
2340 def tell(self):
2341 if not self._seekable:
2342 raise UnsupportedOperation("underlying stream is not seekable")
2343 if not self._telling:
2344 raise OSError("telling position disabled by next() call")
2345 self.flush()
2346 position = self.buffer.tell()
2347 decoder = self._decoder
2348 if decoder is None or self._snapshot is None:
2349 if self._decoded_chars:
2350 # This should never happen.
2351 raise AssertionError("pending decoded text")
2352 return position
2353
2354 # Skip backward to the snapshot point (see _read_chunk).
2355 dec_flags, next_input = self._snapshot
2356 position -= len(next_input)
2357
2358 # How many decoded characters have been used up since the snapshot?
2359 chars_to_skip = self._decoded_chars_used
2360 if chars_to_skip == 0:
2361 # We haven't moved from the snapshot point.
2362 return self._pack_cookie(position, dec_flags)
2363
2364 # Starting from the snapshot position, we will walk the decoder
2365 # forward until it gives us enough decoded characters.
2366 saved_state = decoder.getstate()
2367 try:
2368 # Fast search for an acceptable start point, close to our
2369 # current pos.
2370 # Rationale: calling decoder.decode() has a large overhead
2371 # regardless of chunk size; we want the number of such calls to
2372 # be O(1) in most situations (common decoders, sensible input).
2373 # Actually, it will be exactly 1 for fixed-size codecs (all
2374 # 8-bit codecs, also UTF-16 and UTF-32).
2375 skip_bytes = int(self._b2cratio * chars_to_skip)
2376 skip_back = 1
2377 assert skip_bytes <= len(next_input)
2378 while skip_bytes > 0:
2379 decoder.setstate((b'', dec_flags))
2380 # Decode up to temptative start point
2381 n = len(decoder.decode(next_input[:skip_bytes]))
2382 if n <= chars_to_skip:
2383 b, d = decoder.getstate()
2384 if not b:
2385 # Before pos and no bytes buffered in decoder => OK
2386 dec_flags = d
2387 chars_to_skip -= n
2388 break
2389 # Skip back by buffered amount and reset heuristic
2390 skip_bytes -= len(b)
2391 skip_back = 1
2392 else:
2393 # We're too far ahead, skip back a bit
2394 skip_bytes -= skip_back
2395 skip_back = skip_back * 2
2396 else:
2397 skip_bytes = 0
2398 decoder.setstate((b'', dec_flags))
2399
2400 # Note our initial start point.
2401 start_pos = position + skip_bytes
2402 start_flags = dec_flags
2403 if chars_to_skip == 0:
2404 # We haven't moved from the start point.
2405 return self._pack_cookie(start_pos, start_flags)
2406
2407 # Feed the decoder one byte at a time. As we go, note the
2408 # nearest "safe start point" before the current location
2409 # (a point where the decoder has nothing buffered, so seek()
2410 # can safely start from there and advance to this location).
2411 bytes_fed = 0
2412 need_eof = False
2413 # Chars decoded since `start_pos`
2414 chars_decoded = 0
2415 for i in range(skip_bytes, len(next_input)):
2416 bytes_fed += 1
2417 chars_decoded += len(decoder.decode(next_input[i:i+1]))
2418 dec_buffer, dec_flags = decoder.getstate()
2419 if not dec_buffer and chars_decoded <= chars_to_skip:
2420 # Decoder buffer is empty, so this is a safe start point.
2421 start_pos += bytes_fed
2422 chars_to_skip -= chars_decoded
2423 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
2424 if chars_decoded >= chars_to_skip:
2425 break
2426 else:
2427 # We didn't get enough decoded data; signal EOF to get more.
2428 chars_decoded += len(decoder.decode(b'', final=True))
2429 need_eof = True
2430 if chars_decoded < chars_to_skip:
2431 raise OSError("can't reconstruct logical file position")
2432
2433 # The returned cookie corresponds to the last safe start point.
2434 return self._pack_cookie(
2435 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
2436 finally:
2437 decoder.setstate(saved_state)
2438
2439 def truncate(self, pos=None):
2440 self.flush()
2441 if pos is None:
2442 pos = self.tell()
2443 return self.buffer.truncate(pos)
2444
2445 def detach(self):
2446 if self.buffer is None:
2447 raise ValueError("buffer is already detached")
2448 self.flush()
2449 buffer = self._buffer
2450 self._buffer = None
2451 return buffer
2452
2453 def seek(self, cookie, whence=0):
2454 def _reset_encoder(position):
2455 """Reset the encoder (merely useful for proper BOM handling)"""
2456 try:
2457 encoder = self._encoder or self._get_encoder()
2458 except LookupError:
2459 # Sometimes the encoder doesn't exist
2460 pass
2461 else:
2462 if position != 0:
2463 encoder.setstate(0)
2464 else:
2465 encoder.reset()
2466
2467 if self.closed:
2468 raise ValueError("tell on closed file")
2469 if not self._seekable:
2470 raise UnsupportedOperation("underlying stream is not seekable")
2471 if whence == SEEK_CUR:
2472 if cookie != 0:
2473 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
2474 # Seeking to the current position should attempt to
2475 # sync the underlying buffer with the current position.
2476 whence = 0
2477 cookie = self.tell()
2478 elif whence == SEEK_END:
2479 if cookie != 0:
2480 raise UnsupportedOperation("can't do nonzero end-relative seeks")
2481 self.flush()
2482 position = self.buffer.seek(0, whence)
2483 self._set_decoded_chars('')
2484 self._snapshot = None
2485 if self._decoder:
2486 self._decoder.reset()
2487 _reset_encoder(position)
2488 return position
2489 if whence != 0:
2490 raise ValueError("unsupported whence (%r)" % (whence,))
2491 if cookie < 0:
2492 raise ValueError("negative seek position %r" % (cookie,))
2493 self.flush()
2494
2495 # The strategy of seek() is to go back to the safe start point
2496 # and replay the effect of read(chars_to_skip) from there.
2497 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
2498 self._unpack_cookie(cookie)
2499
2500 # Seek back to the safe start point.
2501 self.buffer.seek(start_pos)
2502 self._set_decoded_chars('')
2503 self._snapshot = None
2504
2505 # Restore the decoder to its state from the safe start point.
2506 if cookie == 0 and self._decoder:
2507 self._decoder.reset()
2508 elif self._decoder or dec_flags or chars_to_skip:
2509 self._decoder = self._decoder or self._get_decoder()
2510 self._decoder.setstate((b'', dec_flags))
2511 self._snapshot = (dec_flags, b'')
2512
2513 if chars_to_skip:
2514 # Just like _read_chunk, feed the decoder and save a snapshot.
2515 input_chunk = self.buffer.read(bytes_to_feed)
2516 self._set_decoded_chars(
2517 self._decoder.decode(input_chunk, need_eof))
2518 self._snapshot = (dec_flags, input_chunk)
2519
2520 # Skip chars_to_skip of the decoded characters.
2521 if len(self._decoded_chars) < chars_to_skip:
2522 raise OSError("can't restore logical file position")
2523 self._decoded_chars_used = chars_to_skip
2524
2525 _reset_encoder(cookie)
2526 return cookie
2527
2528 def read(self, size=None):
2529 self._checkReadable()
2530 if size is None:
2531 size = -1
2532 else:
2533 try:
2534 size_index = size.__index__
2535 except AttributeError:
2536 raise TypeError(f"{size!r} is not an integer")
2537 else:
2538 size = size_index()
2539 decoder = self._decoder or self._get_decoder()
2540 if size < 0:
2541 # Read everything.
2542 result = (self._get_decoded_chars() +
2543 decoder.decode(self.buffer.read(), final=True))
2544 if self._snapshot is not None:
2545 self._set_decoded_chars('')
2546 self._snapshot = None
2547 return result
2548 else:
2549 # Keep reading chunks until we have size characters to return.
2550 eof = False
2551 result = self._get_decoded_chars(size)
2552 while len(result) < size and not eof:
2553 eof = not self._read_chunk()
2554 result += self._get_decoded_chars(size - len(result))
2555 return result
2556
2557 def __next__(self):
2558 self._telling = False
2559 line = self.readline()
2560 if not line:
2561 self._snapshot = None
2562 self._telling = self._seekable
2563 raise StopIteration
2564 return line
2565
2566 def readline(self, size=None):
2567 if self.closed:
2568 raise ValueError("read from closed file")
2569 if size is None:
2570 size = -1
2571 else:
2572 try:
2573 size_index = size.__index__
2574 except AttributeError:
2575 raise TypeError(f"{size!r} is not an integer")
2576 else:
2577 size = size_index()
2578
2579 # Grab all the decoded text (we will rewind any extra bits later).
2580 line = self._get_decoded_chars()
2581
2582 start = 0
2583 # Make the decoder if it doesn't already exist.
2584 if not self._decoder:
2585 self._get_decoder()
2586
2587 pos = endpos = None
2588 while True:
2589 if self._readtranslate:
2590 # Newlines are already translated, only search for \n
2591 pos = line.find('\n', start)
2592 if pos >= 0:
2593 endpos = pos + 1
2594 break
2595 else:
2596 start = len(line)
2597
2598 elif self._readuniversal:
2599 # Universal newline search. Find any of \r, \r\n, \n
2600 # The decoder ensures that \r\n are not split in two pieces
2601
2602 # In C we'd look for these in parallel of course.
2603 nlpos = line.find("\n", start)
2604 crpos = line.find("\r", start)
2605 if crpos == -1:
2606 if nlpos == -1:
2607 # Nothing found
2608 start = len(line)
2609 else:
2610 # Found \n
2611 endpos = nlpos + 1
2612 break
2613 elif nlpos == -1:
2614 # Found lone \r
2615 endpos = crpos + 1
2616 break
2617 elif nlpos < crpos:
2618 # Found \n
2619 endpos = nlpos + 1
2620 break
2621 elif nlpos == crpos + 1:
2622 # Found \r\n
2623 endpos = crpos + 2
2624 break
2625 else:
2626 # Found \r
2627 endpos = crpos + 1
2628 break
2629 else:
2630 # non-universal
2631 pos = line.find(self._readnl)
2632 if pos >= 0:
2633 endpos = pos + len(self._readnl)
2634 break
2635
2636 if size >= 0 and len(line) >= size:
2637 endpos = size # reached length size
2638 break
2639
2640 # No line ending seen yet - get more data'
2641 while self._read_chunk():
2642 if self._decoded_chars:
2643 break
2644 if self._decoded_chars:
2645 line += self._get_decoded_chars()
2646 else:
2647 # end of file
2648 self._set_decoded_chars('')
2649 self._snapshot = None
2650 return line
2651
2652 if size >= 0 and endpos > size:
2653 endpos = size # don't exceed size
2654
2655 # Rewind _decoded_chars to just after the line ending we found.
2656 self._rewind_decoded_chars(len(line) - endpos)
2657 return line[:endpos]
2658
2659 @property
2660 def newlines(self):
2661 return self._decoder.newlines if self._decoder else None
2662
2663
2664 class StringIO(TextIOWrapper):
2665 """Text I/O implementation using an in-memory buffer.
2666
2667 The initial_value argument sets the value of object. The newline
2668 argument is like the one of TextIOWrapper's constructor.
2669 """
2670
2671 def __init__(self, initial_value="", newline="\n"):
2672 super(StringIO, self).__init__(BytesIO(),
2673 encoding="utf-8",
2674 errors="surrogatepass",
2675 newline=newline)
2676 # Issue #5645: make universal newlines semantics the same as in the
2677 # C version, even under Windows.
2678 if newline is None:
2679 self._writetranslate = False
2680 if initial_value is not None:
2681 if not isinstance(initial_value, str):
2682 raise TypeError("initial_value must be str or None, not {0}"
2683 .format(type(initial_value).__name__))
2684 self.write(initial_value)
2685 self.seek(0)
2686
2687 def getvalue(self):
2688 self.flush()
2689 decoder = self._decoder or self._get_decoder()
2690 old_state = decoder.getstate()
2691 decoder.reset()
2692 try:
2693 return decoder.decode(self.buffer.getvalue(), final=True)
2694 finally:
2695 decoder.setstate(old_state)
2696
2697 def __repr__(self):
2698 # TextIOWrapper tells the encoding in its repr. In StringIO,
2699 # that's an implementation detail.
2700 return object.__repr__(self)
2701
2702 @property
2703 def errors(self):
2704 return None
2705
2706 @property
2707 def encoding(self):
2708 return None
2709
2710 def detach(self):
2711 # This doesn't make sense on StringIO.
2712 self._unsupported("detach")