You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2017 lines
67 KiB

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