PageRenderTime 63ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/_pyio.py

http://github.com/IronLanguages/main
Python | 2037 lines | 1937 code | 46 blank | 54 comment | 82 complexity | 371c7fa6cc7fb206d779cce337d3bdc8 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  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 sys
  9. import warnings
  10. import errno
  11. # Import thread instead of threading to reduce startup cost
  12. try:
  13. from thread import allocate_lock as Lock
  14. except ImportError:
  15. from dummy_thread import allocate_lock as Lock
  16. import io
  17. from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
  18. from errno import EINTR
  19. __metaclass__ = type
  20. # open() uses st_blksize whenever we can
  21. DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
  22. # NOTE: Base classes defined here are registered with the "official" ABCs
  23. # defined in io.py. We don't use real inheritance though, because we don't want
  24. # to inherit the C implementations.
  25. class BlockingIOError(IOError):
  26. """Exception raised when I/O would block on a non-blocking I/O stream."""
  27. def __init__(self, errno, strerror, characters_written=0):
  28. super(IOError, self).__init__(errno, strerror)
  29. if not isinstance(characters_written, (int, long)):
  30. raise TypeError("characters_written must be a integer")
  31. self.characters_written = characters_written
  32. def open(file, mode="r", buffering=-1,
  33. encoding=None, errors=None,
  34. newline=None, closefd=True):
  35. r"""Open file and return a stream. Raise IOError upon failure.
  36. file is either a text or byte string giving the name (and the path
  37. if the file isn't in the current working directory) of the file to
  38. be opened or an integer file descriptor of the file to be
  39. wrapped. (If a file descriptor is given, it is closed when the
  40. returned I/O object is closed, unless closefd is set to False.)
  41. mode is an optional string that specifies the mode in which the file
  42. is opened. It defaults to 'r' which means open for reading in text
  43. mode. Other common values are 'w' for writing (truncating the file if
  44. it already exists), and 'a' for appending (which on some Unix systems,
  45. means that all writes append to the end of the file regardless of the
  46. current seek position). In text mode, if encoding is not specified the
  47. encoding used is platform dependent. (For reading and writing raw
  48. bytes use binary mode and leave encoding unspecified.) The available
  49. modes are:
  50. ========= ===============================================================
  51. Character Meaning
  52. --------- ---------------------------------------------------------------
  53. 'r' open for reading (default)
  54. 'w' open for writing, truncating the file first
  55. 'a' open for writing, appending to the end of the file if it exists
  56. 'b' binary mode
  57. 't' text mode (default)
  58. '+' open a disk file for updating (reading and writing)
  59. 'U' universal newline mode (for backwards compatibility; unneeded
  60. for new code)
  61. ========= ===============================================================
  62. The default mode is 'rt' (open for reading text). For binary random
  63. access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  64. 'r+b' opens the file without truncation.
  65. Python distinguishes between files opened in binary and text modes,
  66. even when the underlying operating system doesn't. Files opened in
  67. binary mode (appending 'b' to the mode argument) return contents as
  68. bytes objects without any decoding. In text mode (the default, or when
  69. 't' is appended to the mode argument), the contents of the file are
  70. returned as strings, the bytes having been first decoded using a
  71. platform-dependent encoding or using the specified encoding if given.
  72. buffering is an optional integer used to set the buffering policy.
  73. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
  74. line buffering (only usable in text mode), and an integer > 1 to indicate
  75. the size of a fixed-size chunk buffer. When no buffering argument is
  76. given, the default buffering policy works as follows:
  77. * Binary files are buffered in fixed-size chunks; the size of the buffer
  78. is chosen using a heuristic trying to determine the underlying device's
  79. "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
  80. On many systems, the buffer will typically be 4096 or 8192 bytes long.
  81. * "Interactive" text files (files for which isatty() returns True)
  82. use line buffering. Other text files use the policy described above
  83. for binary files.
  84. encoding is the name of the encoding used to decode or encode the
  85. file. This should only be used in text mode. The default encoding is
  86. platform dependent, but any encoding supported by Python can be
  87. passed. See the codecs module for the list of supported encodings.
  88. errors is an optional string that specifies how encoding errors are to
  89. be handled---this argument should not be used in binary mode. Pass
  90. 'strict' to raise a ValueError exception if there is an encoding error
  91. (the default of None has the same effect), or pass 'ignore' to ignore
  92. errors. (Note that ignoring encoding errors can lead to data loss.)
  93. See the documentation for codecs.register for a list of the permitted
  94. encoding error strings.
  95. newline controls how universal newlines works (it only applies to text
  96. mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
  97. follows:
  98. * On input, if newline is None, universal newlines mode is
  99. enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
  100. these are translated into '\n' before being returned to the
  101. caller. If it is '', universal newline mode is enabled, but line
  102. endings are returned to the caller untranslated. If it has any of
  103. the other legal values, input lines are only terminated by the given
  104. string, and the line ending is returned to the caller untranslated.
  105. * On output, if newline is None, any '\n' characters written are
  106. translated to the system default line separator, os.linesep. If
  107. newline is '', no translation takes place. If newline is any of the
  108. other legal values, any '\n' characters written are translated to
  109. the given string.
  110. If closefd is False, the underlying file descriptor will be kept open
  111. when the file is closed. This does not work when a file name is given
  112. and must be True in that case.
  113. open() returns a file object whose type depends on the mode, and
  114. through which the standard file operations such as reading and writing
  115. are performed. When open() is used to open a file in a text mode ('w',
  116. 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
  117. a file in a binary mode, the returned class varies: in read binary
  118. mode, it returns a BufferedReader; in write binary and append binary
  119. modes, it returns a BufferedWriter, and in read/write mode, it returns
  120. a BufferedRandom.
  121. It is also possible to use a string or bytearray as a file for both
  122. reading and writing. For strings StringIO can be used like a file
  123. opened in a text mode, and for bytes a BytesIO can be used like a file
  124. opened in a binary mode.
  125. """
  126. if not isinstance(file, (basestring, int, long)):
  127. raise TypeError("invalid file: %r" % file)
  128. if not isinstance(mode, basestring):
  129. raise TypeError("invalid mode: %r" % mode)
  130. if not isinstance(buffering, (int, long)):
  131. raise TypeError("invalid buffering: %r" % buffering)
  132. if encoding is not None and not isinstance(encoding, basestring):
  133. raise TypeError("invalid encoding: %r" % encoding)
  134. if errors is not None and not isinstance(errors, basestring):
  135. raise TypeError("invalid errors: %r" % errors)
  136. modes = set(mode)
  137. if modes - set("arwb+tU") or len(mode) > len(modes):
  138. raise ValueError("invalid mode: %r" % mode)
  139. reading = "r" in modes
  140. writing = "w" in modes
  141. appending = "a" in modes
  142. updating = "+" in modes
  143. text = "t" in modes
  144. binary = "b" in modes
  145. if "U" in modes:
  146. if writing or appending:
  147. raise ValueError("can't use U and writing mode at once")
  148. reading = True
  149. if text and binary:
  150. raise ValueError("can't have text and binary mode at once")
  151. if reading + writing + appending > 1:
  152. raise ValueError("can't have read/write/append mode at once")
  153. if not (reading or writing or appending):
  154. raise ValueError("must have exactly one of read/write/append mode")
  155. if binary and encoding is not None:
  156. raise ValueError("binary mode doesn't take an encoding argument")
  157. if binary and errors is not None:
  158. raise ValueError("binary mode doesn't take an errors argument")
  159. if binary and newline is not None:
  160. raise ValueError("binary mode doesn't take a newline argument")
  161. raw = FileIO(file,
  162. (reading and "r" or "") +
  163. (writing and "w" or "") +
  164. (appending and "a" or "") +
  165. (updating and "+" or ""),
  166. closefd)
  167. result = raw
  168. try:
  169. line_buffering = False
  170. if buffering == 1 or buffering < 0 and raw.isatty():
  171. buffering = -1
  172. line_buffering = True
  173. if buffering < 0:
  174. buffering = DEFAULT_BUFFER_SIZE
  175. try:
  176. bs = os.fstat(raw.fileno()).st_blksize
  177. except (os.error, AttributeError):
  178. pass
  179. else:
  180. if bs > 1:
  181. buffering = bs
  182. if buffering < 0:
  183. raise ValueError("invalid buffering size")
  184. if buffering == 0:
  185. if binary:
  186. return result
  187. raise ValueError("can't have unbuffered text I/O")
  188. if updating:
  189. buffer = BufferedRandom(raw, buffering)
  190. elif writing or appending:
  191. buffer = BufferedWriter(raw, buffering)
  192. elif reading:
  193. buffer = BufferedReader(raw, buffering)
  194. else:
  195. raise ValueError("unknown mode: %r" % mode)
  196. result = buffer
  197. if binary:
  198. return result
  199. text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
  200. result = text
  201. text.mode = mode
  202. return result
  203. except:
  204. result.close()
  205. raise
  206. class DocDescriptor:
  207. """Helper for builtins.open.__doc__
  208. """
  209. def __get__(self, obj, typ):
  210. return (
  211. "open(file, mode='r', buffering=-1, encoding=None, "
  212. "errors=None, newline=None, closefd=True)\n\n" +
  213. open.__doc__)
  214. class OpenWrapper:
  215. """Wrapper for builtins.open
  216. Trick so that open won't become a bound method when stored
  217. as a class variable (as dbm.dumb does).
  218. See initstdio() in Python/pythonrun.c.
  219. """
  220. __doc__ = DocDescriptor()
  221. def __new__(cls, *args, **kwargs):
  222. return open(*args, **kwargs)
  223. class UnsupportedOperation(ValueError, IOError):
  224. pass
  225. class IOBase:
  226. __metaclass__ = abc.ABCMeta
  227. """The abstract base class for all I/O classes, acting on streams of
  228. bytes. There is no public constructor.
  229. This class provides dummy implementations for many methods that
  230. derived classes can override selectively; the default implementations
  231. represent a file that cannot be read, written or seeked.
  232. Even though IOBase does not declare read, readinto, or write because
  233. their signatures will vary, implementations and clients should
  234. consider those methods part of the interface. Also, implementations
  235. may raise a IOError when operations they do not support are called.
  236. The basic type used for binary data read from or written to a file is
  237. the bytes type. Method arguments may also be bytearray or memoryview of
  238. arrays of bytes. In some cases, such as readinto, a writable object such
  239. as bytearray is required. Text I/O classes work with unicode data.
  240. Note that calling any method (even inquiries) on a closed stream is
  241. undefined. Implementations may raise IOError in this case.
  242. IOBase (and its subclasses) support the iterator protocol, meaning
  243. that an IOBase object can be iterated over yielding the lines in a
  244. stream.
  245. IOBase also supports the :keyword:`with` statement. In this example,
  246. fp is closed after the suite of the with statement is complete:
  247. with open('spam.txt', 'r') as fp:
  248. fp.write('Spam and eggs!')
  249. """
  250. ### Internal ###
  251. def _unsupported(self, name):
  252. """Internal: raise an exception for unsupported operations."""
  253. raise UnsupportedOperation("%s.%s() not supported" %
  254. (self.__class__.__name__, name))
  255. ### Positioning ###
  256. def seek(self, pos, whence=0):
  257. """Change stream position.
  258. Change the stream position to byte offset pos. Argument pos is
  259. interpreted relative to the position indicated by whence. Values
  260. for whence are:
  261. * 0 -- start of stream (the default); offset should be zero or positive
  262. * 1 -- current stream position; offset may be negative
  263. * 2 -- end of stream; offset is usually negative
  264. Return the new absolute position.
  265. """
  266. self._unsupported("seek")
  267. def tell(self):
  268. """Return current stream position."""
  269. return self.seek(0, 1)
  270. def truncate(self, pos=None):
  271. """Truncate file to size bytes.
  272. Size defaults to the current IO position as reported by tell(). Return
  273. the new size.
  274. """
  275. self._unsupported("truncate")
  276. ### Flush and close ###
  277. def flush(self):
  278. """Flush write buffers, if applicable.
  279. This is not implemented for read-only and non-blocking streams.
  280. """
  281. self._checkClosed()
  282. # XXX Should this return the number of bytes written???
  283. __closed = False
  284. def close(self):
  285. """Flush and close the IO object.
  286. This method has no effect if the file is already closed.
  287. """
  288. if not self.__closed:
  289. try:
  290. self.flush()
  291. finally:
  292. self.__closed = True
  293. def __del__(self):
  294. """Destructor. Calls close()."""
  295. # The try/except block is in case this is called at program
  296. # exit time, when it's possible that globals have already been
  297. # deleted, and then the close() call might fail. Since
  298. # there's nothing we can do about such failures and they annoy
  299. # the end users, we suppress the traceback.
  300. try:
  301. self.close()
  302. except:
  303. pass
  304. ### Inquiries ###
  305. def seekable(self):
  306. """Return whether object supports random access.
  307. If False, seek(), tell() and truncate() will raise IOError.
  308. This method may need to do a test seek().
  309. """
  310. return False
  311. def _checkSeekable(self, msg=None):
  312. """Internal: raise an IOError if file is not seekable
  313. """
  314. if not self.seekable():
  315. raise IOError("File or stream is not seekable."
  316. if msg is None else msg)
  317. def readable(self):
  318. """Return whether object was opened for reading.
  319. If False, read() will raise IOError.
  320. """
  321. return False
  322. def _checkReadable(self, msg=None):
  323. """Internal: raise an IOError if file is not readable
  324. """
  325. if not self.readable():
  326. raise IOError("File or stream is not readable."
  327. if msg is None else msg)
  328. def writable(self):
  329. """Return whether object was opened for writing.
  330. If False, write() and truncate() will raise IOError.
  331. """
  332. return False
  333. def _checkWritable(self, msg=None):
  334. """Internal: raise an IOError if file is not writable
  335. """
  336. if not self.writable():
  337. raise IOError("File or stream is not writable."
  338. if msg is None else msg)
  339. @property
  340. def closed(self):
  341. """closed: bool. True iff the file has been closed.
  342. For backwards compatibility, this is a property, not a predicate.
  343. """
  344. return self.__closed
  345. def _checkClosed(self, msg=None):
  346. """Internal: raise a ValueError if file is closed
  347. """
  348. if self.closed:
  349. raise ValueError("I/O operation on closed file."
  350. if msg is None else msg)
  351. ### Context manager ###
  352. def __enter__(self):
  353. """Context management protocol. Returns self."""
  354. self._checkClosed()
  355. return self
  356. def __exit__(self, *args):
  357. """Context management protocol. Calls close()"""
  358. self.close()
  359. ### Lower-level APIs ###
  360. # XXX Should these be present even if unimplemented?
  361. def fileno(self):
  362. """Returns underlying file descriptor if one exists.
  363. An IOError is raised if the IO object does not use a file descriptor.
  364. """
  365. self._unsupported("fileno")
  366. def isatty(self):
  367. """Return whether this is an 'interactive' stream.
  368. Return False if it can't be determined.
  369. """
  370. self._checkClosed()
  371. return False
  372. ### Readline[s] and writelines ###
  373. def readline(self, limit=-1):
  374. r"""Read and return a line from the stream.
  375. If limit is specified, at most limit bytes will be read.
  376. The line terminator is always b'\n' for binary files; for text
  377. files, the newlines argument to open can be used to select the line
  378. terminator(s) recognized.
  379. """
  380. # For backwards compatibility, a (slowish) readline().
  381. if hasattr(self, "peek"):
  382. def nreadahead():
  383. readahead = self.peek(1)
  384. if not readahead:
  385. return 1
  386. n = (readahead.find(b"\n") + 1) or len(readahead)
  387. if limit >= 0:
  388. n = min(n, limit)
  389. return n
  390. else:
  391. def nreadahead():
  392. return 1
  393. if limit is None:
  394. limit = -1
  395. elif not isinstance(limit, (int, long)):
  396. raise TypeError("limit must be an integer")
  397. res = bytearray()
  398. while limit < 0 or len(res) < limit:
  399. b = self.read(nreadahead())
  400. if not b:
  401. break
  402. res += b
  403. if res.endswith(b"\n"):
  404. break
  405. return bytes(res)
  406. def __iter__(self):
  407. self._checkClosed()
  408. return self
  409. def next(self):
  410. line = self.readline()
  411. if not line:
  412. raise StopIteration
  413. return line
  414. def readlines(self, hint=None):
  415. """Return a list of lines from the stream.
  416. hint can be specified to control the number of lines read: no more
  417. lines will be read if the total size (in bytes/characters) of all
  418. lines so far exceeds hint.
  419. """
  420. if hint is not None and not isinstance(hint, (int, long)):
  421. raise TypeError("integer or None expected")
  422. if hint is None or hint <= 0:
  423. return list(self)
  424. n = 0
  425. lines = []
  426. for line in self:
  427. lines.append(line)
  428. n += len(line)
  429. if n >= hint:
  430. break
  431. return lines
  432. def writelines(self, lines):
  433. self._checkClosed()
  434. for line in lines:
  435. self.write(line)
  436. io.IOBase.register(IOBase)
  437. class RawIOBase(IOBase):
  438. """Base class for raw binary I/O."""
  439. # The read() method is implemented by calling readinto(); derived
  440. # classes that want to support read() only need to implement
  441. # readinto() as a primitive operation. In general, readinto() can be
  442. # more efficient than read().
  443. # (It would be tempting to also provide an implementation of
  444. # readinto() in terms of read(), in case the latter is a more suitable
  445. # primitive operation, but that would lead to nasty recursion in case
  446. # a subclass doesn't implement either.)
  447. def read(self, n=-1):
  448. """Read and return up to n bytes.
  449. Returns an empty bytes object on EOF, or None if the object is
  450. set not to block and has no data to read.
  451. """
  452. if n is None:
  453. n = -1
  454. if n < 0:
  455. return self.readall()
  456. b = bytearray(n.__index__())
  457. n = self.readinto(b)
  458. if n is None:
  459. return None
  460. del b[n:]
  461. return bytes(b)
  462. def readall(self):
  463. """Read until EOF, using multiple read() call."""
  464. res = bytearray()
  465. while True:
  466. data = self.read(DEFAULT_BUFFER_SIZE)
  467. if not data:
  468. break
  469. res += data
  470. if res:
  471. return bytes(res)
  472. else:
  473. # b'' or None
  474. return data
  475. def readinto(self, b):
  476. """Read up to len(b) bytes into b.
  477. Returns number of bytes read (0 for EOF), or None if the object
  478. is set not to block and has no data to read.
  479. """
  480. self._unsupported("readinto")
  481. def write(self, b):
  482. """Write the given buffer to the IO stream.
  483. Returns the number of bytes written, which may be less than len(b).
  484. """
  485. self._unsupported("write")
  486. io.RawIOBase.register(RawIOBase)
  487. from _io import FileIO
  488. RawIOBase.register(FileIO)
  489. class BufferedIOBase(IOBase):
  490. """Base class for buffered IO objects.
  491. The main difference with RawIOBase is that the read() method
  492. supports omitting the size argument, and does not have a default
  493. implementation that defers to readinto().
  494. In addition, read(), readinto() and write() may raise
  495. BlockingIOError if the underlying raw stream is in non-blocking
  496. mode and not ready; unlike their raw counterparts, they will never
  497. return None.
  498. A typical implementation should not inherit from a RawIOBase
  499. implementation, but wrap one.
  500. """
  501. def read(self, n=None):
  502. """Read and return up to n bytes.
  503. If the argument is omitted, None, or negative, reads and
  504. returns all data until EOF.
  505. If the argument is positive, and the underlying raw stream is
  506. not 'interactive', multiple raw reads may be issued to satisfy
  507. the byte count (unless EOF is reached first). But for
  508. interactive raw streams (XXX and for pipes?), at most one raw
  509. read will be issued, and a short result does not imply that
  510. EOF is imminent.
  511. Returns an empty bytes array on EOF.
  512. Raises BlockingIOError if the underlying raw stream has no
  513. data at the moment.
  514. """
  515. self._unsupported("read")
  516. def read1(self, n=None):
  517. """Read up to n bytes with at most one read() system call."""
  518. self._unsupported("read1")
  519. def readinto(self, b):
  520. """Read up to len(b) bytes into b.
  521. Like read(), this may issue multiple reads to the underlying raw
  522. stream, unless the latter is 'interactive'.
  523. Returns the number of bytes read (0 for EOF).
  524. Raises BlockingIOError if the underlying raw stream has no
  525. data at the moment.
  526. """
  527. data = self.read(len(b))
  528. n = len(data)
  529. try:
  530. b[:n] = data
  531. except TypeError as err:
  532. import array
  533. if not isinstance(b, array.array):
  534. raise err
  535. b[:n] = array.array(b'b', data)
  536. return n
  537. def write(self, b):
  538. """Write the given buffer to the IO stream.
  539. Return the number of bytes written, which is always len(b).
  540. Raises BlockingIOError if the buffer is full and the
  541. underlying raw stream cannot accept more data at the moment.
  542. """
  543. self._unsupported("write")
  544. def detach(self):
  545. """
  546. Separate the underlying raw stream from the buffer and return it.
  547. After the raw stream has been detached, the buffer is in an unusable
  548. state.
  549. """
  550. self._unsupported("detach")
  551. io.BufferedIOBase.register(BufferedIOBase)
  552. class _BufferedIOMixin(BufferedIOBase):
  553. """A mixin implementation of BufferedIOBase with an underlying raw stream.
  554. This passes most requests on to the underlying raw stream. It
  555. does *not* provide implementations of read(), readinto() or
  556. write().
  557. """
  558. def __init__(self, raw):
  559. self._raw = raw
  560. ### Positioning ###
  561. def seek(self, pos, whence=0):
  562. new_position = self.raw.seek(pos, whence)
  563. if new_position < 0:
  564. raise IOError("seek() returned an invalid position")
  565. return new_position
  566. def tell(self):
  567. pos = self.raw.tell()
  568. if pos < 0:
  569. raise IOError("tell() returned an invalid position")
  570. return pos
  571. def truncate(self, pos=None):
  572. # Flush the stream. We're mixing buffered I/O with lower-level I/O,
  573. # and a flush may be necessary to synch both views of the current
  574. # file state.
  575. self.flush()
  576. if pos is None:
  577. pos = self.tell()
  578. # XXX: Should seek() be used, instead of passing the position
  579. # XXX directly to truncate?
  580. return self.raw.truncate(pos)
  581. ### Flush and close ###
  582. def flush(self):
  583. if self.closed:
  584. raise ValueError("flush of closed file")
  585. self.raw.flush()
  586. def close(self):
  587. if self.raw is not None and not self.closed:
  588. try:
  589. # may raise BlockingIOError or BrokenPipeError etc
  590. self.flush()
  591. finally:
  592. self.raw.close()
  593. def detach(self):
  594. if self.raw is None:
  595. raise ValueError("raw stream already detached")
  596. self.flush()
  597. raw = self._raw
  598. self._raw = None
  599. return raw
  600. ### Inquiries ###
  601. def seekable(self):
  602. return self.raw.seekable()
  603. def readable(self):
  604. return self.raw.readable()
  605. def writable(self):
  606. return self.raw.writable()
  607. @property
  608. def raw(self):
  609. return self._raw
  610. @property
  611. def closed(self):
  612. return self.raw.closed
  613. @property
  614. def name(self):
  615. return self.raw.name
  616. @property
  617. def mode(self):
  618. return self.raw.mode
  619. def __repr__(self):
  620. clsname = self.__class__.__name__
  621. try:
  622. name = self.name
  623. except Exception:
  624. return "<_pyio.{0}>".format(clsname)
  625. else:
  626. return "<_pyio.{0} name={1!r}>".format(clsname, name)
  627. ### Lower-level APIs ###
  628. def fileno(self):
  629. return self.raw.fileno()
  630. def isatty(self):
  631. return self.raw.isatty()
  632. class BytesIO(BufferedIOBase):
  633. """Buffered I/O implementation using an in-memory bytes buffer."""
  634. def __init__(self, initial_bytes=None):
  635. buf = bytearray()
  636. if initial_bytes is not None:
  637. buf.extend(initial_bytes)
  638. self._buffer = buf
  639. self._pos = 0
  640. def __getstate__(self):
  641. if self.closed:
  642. raise ValueError("__getstate__ on closed file")
  643. return self.__dict__.copy()
  644. def getvalue(self):
  645. """Return the bytes value (contents) of the buffer
  646. """
  647. if self.closed:
  648. raise ValueError("getvalue on closed file")
  649. return bytes(self._buffer)
  650. def read(self, n=None):
  651. if self.closed:
  652. raise ValueError("read from closed file")
  653. if n is None:
  654. n = -1
  655. if not isinstance(n, (int, long)):
  656. raise TypeError("integer argument expected, got {0!r}".format(
  657. type(n)))
  658. if n < 0:
  659. n = len(self._buffer)
  660. if len(self._buffer) <= self._pos:
  661. return b""
  662. newpos = min(len(self._buffer), self._pos + n)
  663. b = self._buffer[self._pos : newpos]
  664. self._pos = newpos
  665. return bytes(b)
  666. def read1(self, n):
  667. """This is the same as read.
  668. """
  669. return self.read(n)
  670. def write(self, b):
  671. if self.closed:
  672. raise ValueError("write to closed file")
  673. if isinstance(b, unicode):
  674. raise TypeError("can't write unicode to binary stream")
  675. n = len(b)
  676. if n == 0:
  677. return 0
  678. pos = self._pos
  679. if pos > len(self._buffer):
  680. # Inserts null bytes between the current end of the file
  681. # and the new write position.
  682. padding = b'\x00' * (pos - len(self._buffer))
  683. self._buffer += padding
  684. self._buffer[pos:pos + n] = b
  685. self._pos += n
  686. return n
  687. def seek(self, pos, whence=0):
  688. if self.closed:
  689. raise ValueError("seek on closed file")
  690. try:
  691. pos.__index__
  692. except AttributeError:
  693. raise TypeError("an integer is required")
  694. if whence == 0:
  695. if pos < 0:
  696. raise ValueError("negative seek position %r" % (pos,))
  697. self._pos = pos
  698. elif whence == 1:
  699. self._pos = max(0, self._pos + pos)
  700. elif whence == 2:
  701. self._pos = max(0, len(self._buffer) + pos)
  702. else:
  703. raise ValueError("invalid whence value")
  704. return self._pos
  705. def tell(self):
  706. if self.closed:
  707. raise ValueError("tell on closed file")
  708. return self._pos
  709. def truncate(self, pos=None):
  710. if self.closed:
  711. raise ValueError("truncate on closed file")
  712. if pos is None:
  713. pos = self._pos
  714. else:
  715. try:
  716. pos.__index__
  717. except AttributeError:
  718. raise TypeError("an integer is required")
  719. if pos < 0:
  720. raise ValueError("negative truncate position %r" % (pos,))
  721. del self._buffer[pos:]
  722. return pos
  723. def readable(self):
  724. if self.closed:
  725. raise ValueError("I/O operation on closed file.")
  726. return True
  727. def writable(self):
  728. if self.closed:
  729. raise ValueError("I/O operation on closed file.")
  730. return True
  731. def seekable(self):
  732. if self.closed:
  733. raise ValueError("I/O operation on closed file.")
  734. return True
  735. class BufferedReader(_BufferedIOMixin):
  736. """BufferedReader(raw[, buffer_size])
  737. A buffer for a readable, sequential BaseRawIO object.
  738. The constructor creates a BufferedReader for the given readable raw
  739. stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
  740. is used.
  741. """
  742. def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
  743. """Create a new buffered reader using the given readable raw IO object.
  744. """
  745. if not raw.readable():
  746. raise IOError('"raw" argument must be readable.')
  747. _BufferedIOMixin.__init__(self, raw)
  748. if buffer_size <= 0:
  749. raise ValueError("invalid buffer size")
  750. self.buffer_size = buffer_size
  751. self._reset_read_buf()
  752. self._read_lock = Lock()
  753. def _reset_read_buf(self):
  754. self._read_buf = b""
  755. self._read_pos = 0
  756. def read(self, n=None):
  757. """Read n bytes.
  758. Returns exactly n bytes of data unless the underlying raw IO
  759. stream reaches EOF or if the call would block in non-blocking
  760. mode. If n is negative, read until EOF or until read() would
  761. block.
  762. """
  763. if n is not None and n < -1:
  764. raise ValueError("invalid number of bytes to read")
  765. with self._read_lock:
  766. return self._read_unlocked(n)
  767. def _read_unlocked(self, n=None):
  768. nodata_val = b""
  769. empty_values = (b"", None)
  770. buf = self._read_buf
  771. pos = self._read_pos
  772. # Special case for when the number of bytes to read is unspecified.
  773. if n is None or n == -1:
  774. self._reset_read_buf()
  775. chunks = [buf[pos:]] # Strip the consumed bytes.
  776. current_size = 0
  777. while True:
  778. # Read until EOF or until read() would block.
  779. try:
  780. chunk = self.raw.read()
  781. except IOError as e:
  782. if e.errno != EINTR:
  783. raise
  784. continue
  785. if chunk in empty_values:
  786. nodata_val = chunk
  787. break
  788. current_size += len(chunk)
  789. chunks.append(chunk)
  790. return b"".join(chunks) or nodata_val
  791. # The number of bytes to read is specified, return at most n bytes.
  792. avail = len(buf) - pos # Length of the available buffered data.
  793. if n <= avail:
  794. # Fast path: the data to read is fully buffered.
  795. self._read_pos += n
  796. return buf[pos:pos+n]
  797. # Slow path: read from the stream until enough bytes are read,
  798. # or until an EOF occurs or until read() would block.
  799. chunks = [buf[pos:]]
  800. wanted = max(self.buffer_size, n)
  801. while avail < n:
  802. try:
  803. chunk = self.raw.read(wanted)
  804. except IOError as e:
  805. if e.errno != EINTR:
  806. raise
  807. continue
  808. if chunk in empty_values:
  809. nodata_val = chunk
  810. break
  811. avail += len(chunk)
  812. chunks.append(chunk)
  813. # n is more than avail only when an EOF occurred or when
  814. # read() would have blocked.
  815. n = min(n, avail)
  816. out = b"".join(chunks)
  817. self._read_buf = out[n:] # Save the extra data in the buffer.
  818. self._read_pos = 0
  819. return out[:n] if out else nodata_val
  820. def peek(self, n=0):
  821. """Returns buffered bytes without advancing the position.
  822. The argument indicates a desired minimal number of bytes; we
  823. do at most one raw read to satisfy it. We never return more
  824. than self.buffer_size.
  825. """
  826. with self._read_lock:
  827. return self._peek_unlocked(n)
  828. def _peek_unlocked(self, n=0):
  829. want = min(n, self.buffer_size)
  830. have = len(self._read_buf) - self._read_pos
  831. if have < want or have <= 0:
  832. to_read = self.buffer_size - have
  833. while True:
  834. try:
  835. current = self.raw.read(to_read)
  836. except IOError as e:
  837. if e.errno != EINTR:
  838. raise
  839. continue
  840. break
  841. if current:
  842. self._read_buf = self._read_buf[self._read_pos:] + current
  843. self._read_pos = 0
  844. return self._read_buf[self._read_pos:]
  845. def read1(self, n):
  846. """Reads up to n bytes, with at most one read() system call."""
  847. # Returns up to n bytes. If at least one byte is buffered, we
  848. # only return buffered bytes. Otherwise, we do one raw read.
  849. if n < 0:
  850. raise ValueError("number of bytes to read must be positive")
  851. if n == 0:
  852. return b""
  853. with self._read_lock:
  854. self._peek_unlocked(1)
  855. return self._read_unlocked(
  856. min(n, len(self._read_buf) - self._read_pos))
  857. def tell(self):
  858. return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
  859. def seek(self, pos, whence=0):
  860. if not (0 <= whence <= 2):
  861. raise ValueError("invalid whence value")
  862. with self._read_lock:
  863. if whence == 1:
  864. pos -= len(self._read_buf) - self._read_pos
  865. pos = _BufferedIOMixin.seek(self, pos, whence)
  866. self._reset_read_buf()
  867. return pos
  868. class BufferedWriter(_BufferedIOMixin):
  869. """A buffer for a writeable sequential RawIO object.
  870. The constructor creates a BufferedWriter for the given writeable raw
  871. stream. If the buffer_size is not given, it defaults to
  872. DEFAULT_BUFFER_SIZE.
  873. """
  874. _warning_stack_offset = 2
  875. def __init__(self, raw,
  876. buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
  877. if not raw.writable():
  878. raise IOError('"raw" argument must be writable.')
  879. _BufferedIOMixin.__init__(self, raw)
  880. if buffer_size <= 0:
  881. raise ValueError("invalid buffer size")
  882. if max_buffer_size is not None:
  883. warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
  884. self._warning_stack_offset)
  885. self.buffer_size = buffer_size
  886. self._write_buf = bytearray()
  887. self._write_lock = Lock()
  888. def write(self, b):
  889. if self.closed:
  890. raise ValueError("write to closed file")
  891. if isinstance(b, unicode):
  892. raise TypeError("can't write unicode to binary stream")
  893. with self._write_lock:
  894. # XXX we can implement some more tricks to try and avoid
  895. # partial writes
  896. if len(self._write_buf) > self.buffer_size:
  897. # We're full, so let's pre-flush the buffer. (This may
  898. # raise BlockingIOError with characters_written == 0.)
  899. self._flush_unlocked()
  900. before = len(self._write_buf)
  901. self._write_buf.extend(b)
  902. written = len(self._write_buf) - before
  903. if len(self._write_buf) > self.buffer_size:
  904. try:
  905. self._flush_unlocked()
  906. except BlockingIOError as e:
  907. if len(self._write_buf) > self.buffer_size:
  908. # We've hit the buffer_size. We have to accept a partial
  909. # write and cut back our buffer.
  910. overage = len(self._write_buf) - self.buffer_size
  911. written -= overage
  912. self._write_buf = self._write_buf[:self.buffer_size]
  913. raise BlockingIOError(e.errno, e.strerror, written)
  914. return written
  915. def truncate(self, pos=None):
  916. with self._write_lock:
  917. self._flush_unlocked()
  918. if pos is None:
  919. pos = self.raw.tell()
  920. return self.raw.truncate(pos)
  921. def flush(self):
  922. with self._write_lock:
  923. self._flush_unlocked()
  924. def _flush_unlocked(self):
  925. if self.closed:
  926. raise ValueError("flush of closed file")
  927. while self._write_buf:
  928. try:
  929. n = self.raw.write(self._write_buf)
  930. except BlockingIOError:
  931. raise RuntimeError("self.raw should implement RawIOBase: it "
  932. "should not raise BlockingIOError")
  933. except IOError as e:
  934. if e.errno != EINTR:
  935. raise
  936. continue
  937. if n is None:
  938. raise BlockingIOError(
  939. errno.EAGAIN,
  940. "write could not complete without blocking", 0)
  941. if n > len(self._write_buf) or n < 0:
  942. raise IOError("write() returned incorrect number of bytes")
  943. del self._write_buf[:n]
  944. def tell(self):
  945. return _BufferedIOMixin.tell(self) + len(self._write_buf)
  946. def seek(self, pos, whence=0):
  947. if not (0 <= whence <= 2):
  948. raise ValueError("invalid whence")
  949. with self._write_lock:
  950. self._flush_unlocked()
  951. return _BufferedIOMixin.seek(self, pos, whence)
  952. class BufferedRWPair(BufferedIOBase):
  953. """A buffered reader and writer object together.
  954. A buffered reader object and buffered writer object put together to
  955. form a sequential IO object that can read and write. This is typically
  956. used with a socket or two-way pipe.
  957. reader and writer are RawIOBase objects that are readable and
  958. writeable respectively. If the buffer_size is omitted it defaults to
  959. DEFAULT_BUFFER_SIZE.
  960. """
  961. # XXX The usefulness of this (compared to having two separate IO
  962. # objects) is questionable.
  963. def __init__(self, reader, writer,
  964. buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
  965. """Constructor.
  966. The arguments are two RawIO instances.
  967. """
  968. if max_buffer_size is not None:
  969. warnings.warn("max_buffer_size is deprecated", DeprecationWarning, 2)
  970. if not reader.readable():
  971. raise IOError('"reader" argument must be readable.')
  972. if not writer.writable():
  973. raise IOError('"writer" argument must be writable.')
  974. self.reader = BufferedReader(reader, buffer_size)
  975. self.writer = BufferedWriter(writer, buffer_size)
  976. def read(self, n=None):
  977. if n is None:
  978. n = -1
  979. return self.reader.read(n)
  980. def readinto(self, b):
  981. return self.reader.readinto(b)
  982. def write(self, b):
  983. return self.writer.write(b)
  984. def peek(self, n=0):
  985. return self.reader.peek(n)
  986. def read1(self, n):
  987. return self.reader.read1(n)
  988. def readable(self):
  989. return self.reader.readable()
  990. def writable(self):
  991. return self.writer.writable()
  992. def flush(self):
  993. return self.writer.flush()
  994. def close(self):
  995. try:
  996. self.writer.close()
  997. finally:
  998. self.reader.close()
  999. def isatty(self):
  1000. return self.reader.isatty() or self.writer.isatty()
  1001. @property
  1002. def closed(self):
  1003. return self.writer.closed
  1004. class BufferedRandom(BufferedWriter, BufferedReader):
  1005. """A buffered interface to random access streams.
  1006. The constructor creates a reader and writer for a seekable stream,
  1007. raw, given in the first argument. If the buffer_size is omitted it
  1008. defaults to DEFAULT_BUFFER_SIZE.
  1009. """
  1010. _warning_stack_offset = 3
  1011. def __init__(self, raw,
  1012. buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
  1013. raw._checkSeekable()
  1014. BufferedReader.__init__(self, raw, buffer_size)
  1015. BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
  1016. def seek(self, pos, whence=0):
  1017. if not (0 <= whence <= 2):
  1018. raise ValueError("invalid whence")
  1019. self.flush()
  1020. if self._read_buf:
  1021. # Undo read ahead.
  1022. with self._read_lock:
  1023. self.raw.seek(self._read_pos - len(self._read_buf), 1)
  1024. # First do the raw seek, then empty the read buffer, so that
  1025. # if the raw seek fails, we don't lose buffered data forever.
  1026. pos = self.raw.seek(pos, whence)
  1027. with self._read_lock:
  1028. self._reset_read_buf()
  1029. if pos < 0:
  1030. raise IOError("seek() returned invalid position")
  1031. return pos
  1032. def tell(self):
  1033. if self._write_buf:
  1034. return BufferedWriter.tell(self)
  1035. else:
  1036. return BufferedReader.tell(self)
  1037. def truncate(self, pos=None):
  1038. if pos is None:
  1039. pos = self.tell()
  1040. # Use seek to flush the read buffer.
  1041. return BufferedWriter.truncate(self, pos)
  1042. def read(self, n=None):
  1043. if n is None:
  1044. n = -1
  1045. self.flush()
  1046. return BufferedReader.read(self, n)
  1047. def readinto(self, b):
  1048. self.flush()
  1049. return BufferedReader.readinto(self, b)
  1050. def peek(self, n=0):
  1051. self.flush()
  1052. return BufferedReader.peek(self, n)
  1053. def read1(self, n):
  1054. self.flush()
  1055. return BufferedReader.read1(self, n)
  1056. def write(self, b):
  1057. if self._read_buf:
  1058. # Undo readahead
  1059. with self._read_lock:
  1060. self.raw.seek(self._read_pos - len(self._read_buf), 1)
  1061. self._reset_read_buf()
  1062. return BufferedWriter.write(self, b)
  1063. class TextIOBase(IOBase):
  1064. """Base class for text I/O.
  1065. This class provides a character and line based interface to stream
  1066. I/O. There is no readinto method because Python's character strings
  1067. are immutable. There is no public constructor.
  1068. """
  1069. def read(self, n=-1):
  1070. """Read at most n characters from stream.
  1071. Read from underlying buffer until we have n characters or we hit EOF.
  1072. If n is negative or omitted, read until EOF.
  1073. """
  1074. self._unsupported("read")
  1075. def write(self, s):
  1076. """Write string s to stream."""
  1077. self._unsupported("write")
  1078. def truncate(self, pos=None):
  1079. """Truncate size to pos."""
  1080. self._unsupported("truncate")
  1081. def readline(self):
  1082. """Read until newline or EOF.
  1083. Returns an empty string if EOF is hit immediately.
  1084. """
  1085. self._unsupported("readline")
  1086. def detach(self):
  1087. """
  1088. Separate the underlying buffer from the TextIOBase and return it.
  1089. After the underlying buffer has been detached, the TextIO is in an
  1090. unusable state.
  1091. """
  1092. self._unsupported("detach")
  1093. @property
  1094. def encoding(self):
  1095. """Subclasses should override."""
  1096. return None
  1097. @property
  1098. def newlines(self):
  1099. """Line endings translated so far.
  1100. Only line endings translated during reading are considered.
  1101. Subclasses should override.
  1102. """
  1103. return None
  1104. @property
  1105. def errors(self):
  1106. """Error setting of the decoder or encoder.
  1107. Subclasses should override."""
  1108. return None
  1109. io.TextIOBase.register(TextIOBase)
  1110. class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
  1111. r"""Codec used when reading a file in universal newlines mode. It wraps
  1112. another incremental decoder, translating \r\n and \r into \n. It also
  1113. records the types of newlines encountered. When used with
  1114. translate=False, it ensures that the newline sequence is returned in
  1115. one piece.
  1116. """
  1117. def __init__(self, decoder, translate, errors='strict'):
  1118. codecs.IncrementalDecoder.__init__(self, errors=errors)
  1119. self.translate = translate
  1120. self.decoder = decoder
  1121. self.seennl = 0
  1122. self.pendingcr = False
  1123. def decode(self, input, final=False):
  1124. # decode input (with the eventual \r from a previous pass)
  1125. if self.decoder is None:
  1126. output = input
  1127. else:
  1128. output = self.decoder.decode(input, final=final)
  1129. if self.pendingcr and (output or final):
  1130. output = "\r" + output
  1131. self.pendingcr = False
  1132. # retain last \r even when not translating data:
  1133. # then readline() is sure to get \r\n in one pass
  1134. if output.endswith("\r") and not final:
  1135. output = output[:-1]
  1136. self.pendingcr = True
  1137. # Record which newlines are read
  1138. crlf = output.count('\r\n')
  1139. cr = output.count('\r') - crlf
  1140. lf = output.count('\n') - crlf
  1141. self.seennl |= (lf and self._LF) | (cr and self._CR) \
  1142. | (crlf and self._CRLF)
  1143. if self.translate:
  1144. if crlf:
  1145. output = output.replace("\r\n", "\n")
  1146. if cr:
  1147. output = output.replace("\r", "\n")
  1148. return output
  1149. def getstate(self):
  1150. if self.decoder is None:
  1151. buf = b""
  1152. flag = 0
  1153. else:
  1154. buf, flag = self.decoder.getstate()
  1155. flag <<= 1
  1156. if self.pendingcr:
  1157. flag |= 1
  1158. return buf, flag
  1159. def setstate(self, state):
  1160. buf, flag = state
  1161. self.pendingcr = bool(flag & 1)
  1162. if self.decoder is not None:
  1163. self.decoder.setstate((buf, flag >> 1))
  1164. def reset(self):
  1165. self.seennl = 0
  1166. self.pendingcr = False
  1167. if self.decoder is not None:
  1168. self.decoder.reset()
  1169. _LF = 1
  1170. _CR = 2
  1171. _CRLF = 4
  1172. @property
  1173. def newlines(self):
  1174. return (None,
  1175. "\n",
  1176. "\r",
  1177. ("\r", "\n"),
  1178. "\r\n",
  1179. ("\n", "\r\n"),
  1180. ("\r", "\r\n"),
  1181. ("\r", "\n", "\r\n")
  1182. )[self.seennl]
  1183. class TextIOWrapper(TextIOBase):
  1184. r"""Character and line based layer over a BufferedIOBase object, buffer.
  1185. encoding gives the name of the encoding that the stream will be
  1186. decoded or encoded with. It defaults to locale.getpreferredencoding.
  1187. errors determines the strictness of encoding and decoding (see the
  1188. codecs.register) and defaults to "strict".
  1189. newline can be None, '', '\n', '\r', or '\r\n'. It controls the
  1190. handling of line endings. If it is None, universal newlines is
  1191. enabled. With this enabled, on input, the lines endings '\n', '\r',
  1192. or '\r\n' are translated to '\n' before being returned to the
  1193. caller. Conversely, on output, '\n' is translated to the system
  1194. default line separator, os.linesep. If newline is any other of its
  1195. legal values, that newline becomes the newline when the file is read
  1196. and it is returned untranslated. On output, '\n' is converted to the
  1197. newline.
  1198. If line_buffering is True, a call to flush is implied when a call to
  1199. write contains a newline character.
  1200. """
  1201. _CHUNK_SIZE = 2048
  1202. def __init__(self, buffer, encoding=None, errors=None, newline=None,
  1203. line_buffering=False):
  1204. if newline is not None and not isinstance(newline, basestring):
  1205. raise TypeError("illegal newline type: %r" % (type(newline),))
  1206. if newline not in (None, "", "\n", "\r", "\r\n"):
  1207. raise ValueError("illegal newline value: %r" % (newline,))
  1208. if encoding is None:
  1209. try:
  1210. import locale
  1211. except ImportError:
  1212. # Importing locale may fail if Python is being built
  1213. encoding = "ascii"
  1214. else:
  1215. encoding = locale.getpreferredencoding()
  1216. if not isinstance(encoding, basestring):
  1217. raise ValueError("invalid encoding: %r" % encoding)
  1218. if sys.py3kwarning and not codecs.lookup(encoding)._is_text_encoding:
  1219. msg = ("%r is not a text encoding; "
  1220. "use codecs.open() to handle ar…

Large files files are truncated, but you can click here to view the full file