logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

_pyio.py (94563B)


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