PageRenderTime 57ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/io.py

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