Back to index

python3.2  3.2.2
Public Member Functions | Private Member Functions | Private Attributes | Static Private Attributes
_pyio.TextIOWrapper Class Reference
Inheritance diagram for _pyio.TextIOWrapper:
Inheritance graph
[legend]
Collaboration diagram for _pyio.TextIOWrapper:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def __repr__
def encoding
def errors
def line_buffering
def buffer
def seekable
 Inquiries ###.
def readable
def writable
def flush
 Flush and close ###.
def close
def closed
def name
def fileno
 Lower-level APIs ###.
def isatty
def write
def tell
def truncate
def detach
def seek
 Positioning ###.
def read
def __next__
def readline
 Readline[s] and writelines ###.
def newlines
def readline
def __enter__
 Context manager ###.
def __exit__
def __iter__
def readlines
def writelines
def __new__
def register
def __instancecheck__
def __subclasscheck__

Private Member Functions

def _get_encoder
def _get_decoder
def _set_decoded_chars
def _get_decoded_chars
def _rewind_decoded_chars
def _read_chunk
def _pack_cookie
def _unpack_cookie

Private Attributes

 _buffer
 _line_buffering
 _encoding
 _errors
 _readuniversal
 _readtranslate
 _readnl
 _writetranslate
 _writenl
 _encoder
 _decoder
 _decoded_chars
 _decoded_chars_used
 _snapshot
 _seekable
 _telling
 _has_read1

Static Private Attributes

int _CHUNK_SIZE = 2048

Detailed Description

Definition at line 1448 of file _pyio.py.


Constructor & Destructor Documentation

def _pyio.TextIOWrapper.__init__ (   self,
  buffer,
  encoding = None,
  errors = None,
  newline = None,
  line_buffering = False,
  write_through = False 
)

Definition at line 1475 of file _pyio.py.

01475 
01476                  line_buffering=False, write_through=False):
01477         if newline is not None and not isinstance(newline, str):
01478             raise TypeError("illegal newline type: %r" % (type(newline),))
01479         if newline not in (None, "", "\n", "\r", "\r\n"):
01480             raise ValueError("illegal newline value: %r" % (newline,))
01481         if encoding is None:
01482             try:
01483                 encoding = os.device_encoding(buffer.fileno())
01484             except (AttributeError, UnsupportedOperation):
01485                 pass
01486             if encoding is None:
01487                 try:
01488                     import locale
01489                 except ImportError:
01490                     # Importing locale may fail if Python is being built
01491                     encoding = "ascii"
01492                 else:
01493                     encoding = locale.getpreferredencoding()
01494 
01495         if not isinstance(encoding, str):
01496             raise ValueError("invalid encoding: %r" % encoding)
01497 
01498         if errors is None:
01499             errors = "strict"
01500         else:
01501             if not isinstance(errors, str):
01502                 raise ValueError("invalid errors: %r" % errors)
01503 
01504         self._buffer = buffer
01505         self._line_buffering = line_buffering
01506         self._encoding = encoding
01507         self._errors = errors
01508         self._readuniversal = not newline
01509         self._readtranslate = newline is None
01510         self._readnl = newline
01511         self._writetranslate = newline != ''
01512         self._writenl = newline or os.linesep
01513         self._encoder = None
01514         self._decoder = None
01515         self._decoded_chars = ''  # buffer for text returned from decoder
01516         self._decoded_chars_used = 0  # offset into _decoded_chars for read()
01517         self._snapshot = None  # info for reconstructing decoder state
01518         self._seekable = self._telling = self.buffer.seekable()
01519         self._has_read1 = hasattr(self.buffer, 'read1')
01520 
01521         if self._seekable and self.writable():
01522             position = self.buffer.tell()
01523             if position != 0:
01524                 try:
01525                     self._get_encoder().setstate(0)
01526                 except LookupError:
01527                     # Sometimes the encoder doesn't exist
01528                     pass

Here is the call graph for this function:

Here is the caller graph for this function:


Member Function Documentation

def _pyio.IOBase.__enter__ (   self) [inherited]

Context manager ###.

Context management protocol.  Returns self (an instance of IOBase).

Definition at line 419 of file _pyio.py.

00419 
00420     def __enter__(self):  # That's a forward reference
00421         """Context management protocol.  Returns self (an instance of IOBase)."""
00422         self._checkClosed()
00423         return self

Here is the call graph for this function:

def _pyio.IOBase.__exit__ (   self,
  args 
) [inherited]
Context management protocol.  Calls close()

Definition at line 424 of file _pyio.py.

00424 
00425     def __exit__(self, *args):
00426         """Context management protocol.  Calls close()"""
00427         self.close()

Here is the call graph for this function:

Here is the caller graph for this function:

def abc.ABCMeta.__instancecheck__ (   cls,
  instance 
) [inherited]
Override for isinstance(instance, cls).

Definition at line 158 of file abc.py.

00158 
00159     def __instancecheck__(cls, instance):
00160         """Override for isinstance(instance, cls)."""
00161         # Inline the cache checking
00162         subclass = instance.__class__
00163         if subclass in cls._abc_cache:
00164             return True
00165         subtype = type(instance)
00166         if subtype is subclass:
00167             if (cls._abc_negative_cache_version ==
00168                 ABCMeta._abc_invalidation_counter and
00169                 subclass in cls._abc_negative_cache):
00170                 return False
00171             # Fall back to the subclass check.
00172             return cls.__subclasscheck__(subclass)
00173         return any(cls.__subclasscheck__(c) for c in {subclass, subtype})

Here is the call graph for this function:

def _pyio.IOBase.__iter__ (   self) [inherited]

Definition at line 486 of file _pyio.py.

00486 
00487     def __iter__(self):
00488         self._checkClosed()
00489         return self

Here is the call graph for this function:

def abc.ABCMeta.__new__ (   mcls,
  name,
  bases,
  namespace 
) [inherited]

Definition at line 116 of file abc.py.

00116 
00117     def __new__(mcls, name, bases, namespace):
00118         cls = super().__new__(mcls, name, bases, namespace)
00119         # Compute set of abstract method names
00120         abstracts = {name
00121                      for name, value in namespace.items()
00122                      if getattr(value, "__isabstractmethod__", False)}
00123         for base in bases:
00124             for name in getattr(base, "__abstractmethods__", set()):
00125                 value = getattr(cls, name, None)
00126                 if getattr(value, "__isabstractmethod__", False):
00127                     abstracts.add(name)
00128         cls.__abstractmethods__ = frozenset(abstracts)
00129         # Set up inheritance registry
00130         cls._abc_registry = WeakSet()
00131         cls._abc_cache = WeakSet()
00132         cls._abc_negative_cache = WeakSet()
00133         cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
00134         return cls

Here is the call graph for this function:

Reimplemented from _pyio.IOBase.

Definition at line 1889 of file _pyio.py.

01889 
01890     def __next__(self):
01891         self._telling = False
01892         line = self.readline()
01893         if not line:
01894             self._snapshot = None
01895             self._telling = self._seekable
01896             raise StopIteration
01897         return line

Here is the call graph for this function:

Here is the caller graph for this function:

Reimplemented in _pyio.StringIO.

Definition at line 1538 of file _pyio.py.

01538 
01539     def __repr__(self):
01540         result = "<_pyio.TextIOWrapper"
01541         try:
01542             name = self.name
01543         except AttributeError:
01544             pass
01545         else:
01546             result += " name={0!r}".format(name)
01547         try:
01548             mode = self.mode
01549         except AttributeError:
01550             pass
01551         else:
01552             result += " mode={0!r}".format(mode)
01553         return result + " encoding={0!r}>".format(self.encoding)

Here is the call graph for this function:

def abc.ABCMeta.__subclasscheck__ (   cls,
  subclass 
) [inherited]
Override for issubclass(subclass, cls).

Definition at line 174 of file abc.py.

00174 
00175     def __subclasscheck__(cls, subclass):
00176         """Override for issubclass(subclass, cls)."""
00177         # Check cache
00178         if subclass in cls._abc_cache:
00179             return True
00180         # Check negative cache; may have to invalidate
00181         if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
00182             # Invalidate the negative cache
00183             cls._abc_negative_cache = WeakSet()
00184             cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
00185         elif subclass in cls._abc_negative_cache:
00186             return False
00187         # Check the subclass hook
00188         ok = cls.__subclasshook__(subclass)
00189         if ok is not NotImplemented:
00190             assert isinstance(ok, bool)
00191             if ok:
00192                 cls._abc_cache.add(subclass)
00193             else:
00194                 cls._abc_negative_cache.add(subclass)
00195             return ok
00196         # Check if it's a direct subclass
00197         if cls in getattr(subclass, '__mro__', ()):
00198             cls._abc_cache.add(subclass)
00199             return True
00200         # Check if it's a subclass of a registered class (recursive)
00201         for rcls in cls._abc_registry:
00202             if issubclass(subclass, rcls):
00203                 cls._abc_cache.add(subclass)
00204                 return True
00205         # Check if it's a subclass of a subclass (recursive)
00206         for scls in cls.__subclasses__():
00207             if issubclass(subclass, scls):
00208                 cls._abc_cache.add(subclass)
00209                 return True
00210         # No dice; update negative cache
00211         cls._abc_negative_cache.add(subclass)
00212         return False

Here is the call graph for this function:

def _pyio.TextIOWrapper._get_decoded_chars (   self,
  n = None 
) [private]
Advance into the _decoded_chars buffer.

Definition at line 1645 of file _pyio.py.

01645 
01646     def _get_decoded_chars(self, n=None):
01647         """Advance into the _decoded_chars buffer."""
01648         offset = self._decoded_chars_used
01649         if n is None:
01650             chars = self._decoded_chars[offset:]
01651         else:
01652             chars = self._decoded_chars[offset:offset + n]
01653         self._decoded_chars_used += len(chars)
01654         return chars

def _pyio.TextIOWrapper._get_decoder (   self) [private]

Definition at line 1629 of file _pyio.py.

01629 
01630     def _get_decoder(self):
01631         make_decoder = codecs.getincrementaldecoder(self._encoding)
01632         decoder = make_decoder(self._errors)
01633         if self._readuniversal:
01634             decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
01635         self._decoder = decoder
01636         return decoder

Here is the call graph for this function:

def _pyio.TextIOWrapper._get_encoder (   self) [private]

Definition at line 1624 of file _pyio.py.

01624 
01625     def _get_encoder(self):
01626         make_encoder = codecs.getincrementalencoder(self._encoding)
01627         self._encoder = make_encoder(self._errors)
01628         return self._encoder

Here is the call graph for this function:

Here is the caller graph for this function:

def _pyio.TextIOWrapper._pack_cookie (   self,
  position,
  dec_flags = 0,
  bytes_to_feed = 0,
  need_eof = 0,
  chars_to_skip = 0 
) [private]

Definition at line 1699 of file _pyio.py.

01699 
01700                            bytes_to_feed=0, need_eof=0, chars_to_skip=0):
01701         # The meaning of a tell() cookie is: seek to position, set the
01702         # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
01703         # into the decoder with need_eof as the EOF flag, then skip
01704         # chars_to_skip characters of the decoded result.  For most simple
01705         # decoders, tell() will often just give a byte offset in the file.
01706         return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
01707                (chars_to_skip<<192) | bool(need_eof)<<256)

def _pyio.TextIOWrapper._read_chunk (   self) [private]
Read and decode the next chunk of data from the BufferedReader.

Definition at line 1661 of file _pyio.py.

01661 
01662     def _read_chunk(self):
01663         """
01664         Read and decode the next chunk of data from the BufferedReader.
01665         """
01666 
01667         # The return value is True unless EOF was reached.  The decoded
01668         # string is placed in self._decoded_chars (replacing its previous
01669         # value).  The entire input chunk is sent to the decoder, though
01670         # some of it may remain buffered in the decoder, yet to be
01671         # converted.
01672 
01673         if self._decoder is None:
01674             raise ValueError("no decoder")
01675 
01676         if self._telling:
01677             # To prepare for tell(), we need to snapshot a point in the
01678             # file where the decoder's input buffer is empty.
01679 
01680             dec_buffer, dec_flags = self._decoder.getstate()
01681             # Given this, we know there was a valid snapshot point
01682             # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
01683 
01684         # Read a chunk, decode it, and put the result in self._decoded_chars.
01685         if self._has_read1:
01686             input_chunk = self.buffer.read1(self._CHUNK_SIZE)
01687         else:
01688             input_chunk = self.buffer.read(self._CHUNK_SIZE)
01689         eof = not input_chunk
01690         self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
01691 
01692         if self._telling:
01693             # At the snapshot point, len(dec_buffer) bytes before the read,
01694             # the next input to be decoded is dec_buffer + input_chunk.
01695             self._snapshot = (dec_flags, dec_buffer + input_chunk)
01696 
01697         return not eof

Here is the call graph for this function:

def _pyio.TextIOWrapper._rewind_decoded_chars (   self,
  n 
) [private]
Rewind the _decoded_chars buffer.

Definition at line 1655 of file _pyio.py.

01655 
01656     def _rewind_decoded_chars(self, n):
01657         """Rewind the _decoded_chars buffer."""
01658         if self._decoded_chars_used < n:
01659             raise AssertionError("rewind decoded_chars out of bounds")
01660         self._decoded_chars_used -= n

def _pyio.TextIOWrapper._set_decoded_chars (   self,
  chars 
) [private]
Set the _decoded_chars buffer.

Definition at line 1640 of file _pyio.py.

01640 
01641     def _set_decoded_chars(self, chars):
01642         """Set the _decoded_chars buffer."""
01643         self._decoded_chars = chars
01644         self._decoded_chars_used = 0

Here is the caller graph for this function:

def _pyio.TextIOWrapper._unpack_cookie (   self,
  bigint 
) [private]

Definition at line 1708 of file _pyio.py.

01708 
01709     def _unpack_cookie(self, bigint):
01710         rest, position = divmod(bigint, 1<<64)
01711         rest, dec_flags = divmod(rest, 1<<64)
01712         rest, bytes_to_feed = divmod(rest, 1<<64)
01713         need_eof, chars_to_skip = divmod(rest, 1<<64)
01714         return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip

Here is the call graph for this function:

Definition at line 1567 of file _pyio.py.

01567 
01568     def buffer(self):
01569         return self._buffer

def _pyio.TextIOWrapper.close (   self)
Flush and close the IO object.

This method has no effect if the file is already closed.

Reimplemented from _pyio.IOBase.

Definition at line 1583 of file _pyio.py.

01583 
01584     def close(self):
01585         if self.buffer is not None and not self.closed:
01586             self.flush()
01587             self.buffer.close()

Here is the call graph for this function:

closed: bool.  True iff the file has been closed.

For backwards compatibility, this is a property, not a predicate.

Reimplemented from _pyio.IOBase.

Definition at line 1589 of file _pyio.py.

01589 
01590     def closed(self):
01591         return self.buffer.closed

Here is the caller graph for this function:

Separate the underlying buffer from the TextIOBase and return it.

After the underlying buffer has been detached, the TextIO is in an
unusable state.

Reimplemented from _pyio.TextIOBase.

Reimplemented in _pyio.StringIO.

Definition at line 1784 of file _pyio.py.

01784 
01785     def detach(self):
01786         if self.buffer is None:
01787             raise ValueError("buffer is already detached")
01788         self.flush()
01789         buffer = self._buffer
01790         self._buffer = None
01791         return buffer

Here is the call graph for this function:

Here is the caller graph for this function:

Subclasses should override.

Reimplemented from _pyio.TextIOBase.

Reimplemented in _pyio.StringIO.

Definition at line 1555 of file _pyio.py.

01555 
01556     def encoding(self):
01557         return self._encoding

Here is the caller graph for this function:

Error setting of the decoder or encoder.

Subclasses should override.

Reimplemented from _pyio.TextIOBase.

Reimplemented in _pyio.StringIO.

Definition at line 1559 of file _pyio.py.

01559 
01560     def errors(self):
01561         return self._errors

Lower-level APIs ###.

Returns underlying file descriptor (an int) if one exists.

An IOError is raised if the IO object does not use a file descriptor.

Reimplemented from _pyio.IOBase.

Definition at line 1596 of file _pyio.py.

01596 
01597     def fileno(self):
01598         return self.buffer.fileno()

Here is the caller graph for this function:

def _pyio.TextIOWrapper.flush (   self)

Flush and close ###.

Flush write buffers, if applicable.

This is not implemented for read-only and non-blocking streams.

Reimplemented from _pyio.IOBase.

Definition at line 1579 of file _pyio.py.

01579 
01580     def flush(self):
01581         self.buffer.flush()
01582         self._telling = self._seekable

Here is the caller graph for this function:

Return a bool indicating whether this is an 'interactive' stream.

Return False if it can't be determined.

Reimplemented from _pyio.IOBase.

Definition at line 1599 of file _pyio.py.

01599 
01600     def isatty(self):
01601         return self.buffer.isatty()

Definition at line 1563 of file _pyio.py.

01563 
01564     def line_buffering(self):
01565         return self._line_buffering

def _pyio.TextIOWrapper.name (   self)

Definition at line 1593 of file _pyio.py.

01593 
01594     def name(self):
01595         return self.buffer.name

Here is the caller graph for this function:

Line endings translated so far.

Only line endings translated during reading are considered.

Subclasses should override.

Reimplemented from _pyio.TextIOBase.

Definition at line 1987 of file _pyio.py.

01987 
01988     def newlines(self):
01989         return self._decoder.newlines if self._decoder else None
01990 

def _pyio.TextIOWrapper.read (   self,
  n = None 
)
Read at most n characters from stream, where n is an int.

Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.

Returns a string.

Reimplemented from _pyio.TextIOBase.

Definition at line 1864 of file _pyio.py.

01864 
01865     def read(self, n=None):
01866         self._checkReadable()
01867         if n is None:
01868             n = -1
01869         decoder = self._decoder or self._get_decoder()
01870         try:
01871             n.__index__
01872         except AttributeError as err:
01873             raise TypeError("an integer is required") from err
01874         if n < 0:
01875             # Read everything.
01876             result = (self._get_decoded_chars() +
01877                       decoder.decode(self.buffer.read(), final=True))
01878             self._set_decoded_chars('')
01879             self._snapshot = None
01880             return result
01881         else:
01882             # Keep reading chunks until we have n characters to return.
01883             eof = False
01884             result = self._get_decoded_chars(n)
01885             while len(result) < n and not eof:
01886                 eof = not self._read_chunk()
01887                 result += self._get_decoded_chars(n - len(result))
01888             return result

Here is the call graph for this function:

Here is the caller graph for this function:

Return a bool indicating whether object was opened for reading.

If False, read() will raise UnsupportedOperation.

Reimplemented from _pyio.IOBase.

Definition at line 1573 of file _pyio.py.

01573 
01574     def readable(self):
01575         return self.buffer.readable()

def _pyio.TextIOBase.readline (   self) [inherited]
Read until newline or EOF.

Returns an empty string if EOF is hit immediately.

Definition at line 1322 of file _pyio.py.

01322 
01323     def readline(self):
01324         """Read until newline or EOF.
01325 
01326         Returns an empty string if EOF is hit immediately.
01327         """
01328         self._unsupported("readline")

Here is the call graph for this function:

Here is the caller graph for this function:

def _pyio.TextIOWrapper.readline (   self,
  limit = None 
)

Readline[s] and writelines ###.

Reimplemented from _pyio.IOBase.

Definition at line 1898 of file _pyio.py.

01898 
01899     def readline(self, limit=None):
01900         if self.closed:
01901             raise ValueError("read from closed file")
01902         if limit is None:
01903             limit = -1
01904         elif not isinstance(limit, int):
01905             raise TypeError("limit must be an integer")
01906 
01907         # Grab all the decoded text (we will rewind any extra bits later).
01908         line = self._get_decoded_chars()
01909 
01910         start = 0
01911         # Make the decoder if it doesn't already exist.
01912         if not self._decoder:
01913             self._get_decoder()
01914 
01915         pos = endpos = None
01916         while True:
01917             if self._readtranslate:
01918                 # Newlines are already translated, only search for \n
01919                 pos = line.find('\n', start)
01920                 if pos >= 0:
01921                     endpos = pos + 1
01922                     break
01923                 else:
01924                     start = len(line)
01925 
01926             elif self._readuniversal:
01927                 # Universal newline search. Find any of \r, \r\n, \n
01928                 # The decoder ensures that \r\n are not split in two pieces
01929 
01930                 # In C we'd look for these in parallel of course.
01931                 nlpos = line.find("\n", start)
01932                 crpos = line.find("\r", start)
01933                 if crpos == -1:
01934                     if nlpos == -1:
01935                         # Nothing found
01936                         start = len(line)
01937                     else:
01938                         # Found \n
01939                         endpos = nlpos + 1
01940                         break
01941                 elif nlpos == -1:
01942                     # Found lone \r
01943                     endpos = crpos + 1
01944                     break
01945                 elif nlpos < crpos:
01946                     # Found \n
01947                     endpos = nlpos + 1
01948                     break
01949                 elif nlpos == crpos + 1:
01950                     # Found \r\n
01951                     endpos = crpos + 2
01952                     break
01953                 else:
01954                     # Found \r
01955                     endpos = crpos + 1
01956                     break
01957             else:
01958                 # non-universal
01959                 pos = line.find(self._readnl)
01960                 if pos >= 0:
01961                     endpos = pos + len(self._readnl)
01962                     break
01963 
01964             if limit >= 0 and len(line) >= limit:
01965                 endpos = limit  # reached length limit
01966                 break
01967 
01968             # No line ending seen yet - get more data'
01969             while self._read_chunk():
01970                 if self._decoded_chars:
01971                     break
01972             if self._decoded_chars:
01973                 line += self._get_decoded_chars()
01974             else:
01975                 # end of file
01976                 self._set_decoded_chars('')
01977                 self._snapshot = None
01978                 return line
01979 
01980         if limit >= 0 and endpos > limit:
01981             endpos = limit  # don't exceed limit
01982 
01983         # Rewind _decoded_chars to just after the line ending we found.
01984         self._rewind_decoded_chars(len(line) - endpos)
01985         return line[:endpos]

Here is the call graph for this function:

Here is the caller graph for this function:

def _pyio.IOBase.readlines (   self,
  hint = None 
) [inherited]
Return a list of lines from the stream.

hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.

Definition at line 496 of file _pyio.py.

00496 
00497     def readlines(self, hint=None):
00498         """Return a list of lines from the stream.
00499 
00500         hint can be specified to control the number of lines read: no more
00501         lines will be read if the total size (in bytes/characters) of all
00502         lines so far exceeds hint.
00503         """
00504         if hint is None or hint <= 0:
00505             return list(self)
00506         n = 0
00507         lines = []
00508         for line in self:
00509             lines.append(line)
00510             n += len(line)
00511             if n >= hint:
00512                 break
00513         return lines

def abc.ABCMeta.register (   cls,
  subclass 
) [inherited]
Register a virtual subclass of an ABC.

Definition at line 135 of file abc.py.

00135 
00136     def register(cls, subclass):
00137         """Register a virtual subclass of an ABC."""
00138         if not isinstance(subclass, type):
00139             raise TypeError("Can only register classes")
00140         if issubclass(subclass, cls):
00141             return  # Already a subclass
00142         # Subtle: test for cycles *after* testing for "already a subclass";
00143         # this means we allow X.register(X) and interpret it as a no-op.
00144         if issubclass(cls, subclass):
00145             # This would create a cycle, which is bad for the algorithm below
00146             raise RuntimeError("Refusing to create an inheritance cycle")
00147         cls._abc_registry.add(subclass)
00148         ABCMeta._abc_invalidation_counter += 1  # Invalidate negative cache

Here is the caller graph for this function:

def _pyio.TextIOWrapper.seek (   self,
  pos,
  whence = 0 
)

Positioning ###.

Change stream position.

Change the stream position to byte offset offset. offset is
interpreted relative to the position indicated by whence.  Values
for whence are ints:

* 0 -- start of stream (the default); offset should be zero or positive
* 1 -- current stream position; offset may be negative
* 2 -- end of stream; offset is usually negative

Return an int indicating the new absolute position.

Reimplemented from _pyio.IOBase.

Definition at line 1792 of file _pyio.py.

01792 
01793     def seek(self, cookie, whence=0):
01794         if self.closed:
01795             raise ValueError("tell on closed file")
01796         if not self._seekable:
01797             raise UnsupportedOperation("underlying stream is not seekable")
01798         if whence == 1: # seek relative to current position
01799             if cookie != 0:
01800                 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
01801             # Seeking to the current position should attempt to
01802             # sync the underlying buffer with the current position.
01803             whence = 0
01804             cookie = self.tell()
01805         if whence == 2: # seek relative to end of file
01806             if cookie != 0:
01807                 raise UnsupportedOperation("can't do nonzero end-relative seeks")
01808             self.flush()
01809             position = self.buffer.seek(0, 2)
01810             self._set_decoded_chars('')
01811             self._snapshot = None
01812             if self._decoder:
01813                 self._decoder.reset()
01814             return position
01815         if whence != 0:
01816             raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
01817                              (whence,))
01818         if cookie < 0:
01819             raise ValueError("negative seek position %r" % (cookie,))
01820         self.flush()
01821 
01822         # The strategy of seek() is to go back to the safe start point
01823         # and replay the effect of read(chars_to_skip) from there.
01824         start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
01825             self._unpack_cookie(cookie)
01826 
01827         # Seek back to the safe start point.
01828         self.buffer.seek(start_pos)
01829         self._set_decoded_chars('')
01830         self._snapshot = None
01831 
01832         # Restore the decoder to its state from the safe start point.
01833         if cookie == 0 and self._decoder:
01834             self._decoder.reset()
01835         elif self._decoder or dec_flags or chars_to_skip:
01836             self._decoder = self._decoder or self._get_decoder()
01837             self._decoder.setstate((b'', dec_flags))
01838             self._snapshot = (dec_flags, b'')
01839 
01840         if chars_to_skip:
01841             # Just like _read_chunk, feed the decoder and save a snapshot.
01842             input_chunk = self.buffer.read(bytes_to_feed)
01843             self._set_decoded_chars(
01844                 self._decoder.decode(input_chunk, need_eof))
01845             self._snapshot = (dec_flags, input_chunk)
01846 
01847             # Skip chars_to_skip of the decoded characters.
01848             if len(self._decoded_chars) < chars_to_skip:
01849                 raise IOError("can't restore logical file position")
01850             self._decoded_chars_used = chars_to_skip
01851 
01852         # Finally, reset the encoder (merely useful for proper BOM handling)
01853         try:
01854             encoder = self._encoder or self._get_encoder()
01855         except LookupError:
01856             # Sometimes the encoder doesn't exist
01857             pass
01858         else:
01859             if cookie != 0:
01860                 encoder.setstate(0)
01861             else:
01862                 encoder.reset()
01863         return cookie

Here is the call graph for this function:

Here is the caller graph for this function:

Inquiries ###.

Return a bool indicating whether object supports random access.

If False, seek(), tell() and truncate() will raise UnsupportedOperation.
This method may need to do a test seek().

Reimplemented from _pyio.IOBase.

Definition at line 1570 of file _pyio.py.

01570 
01571     def seekable(self):
01572         return self._seekable

def _pyio.TextIOWrapper.tell (   self)
Return an int indicating the current stream position.

Reimplemented from _pyio.IOBase.

Definition at line 1715 of file _pyio.py.

01715 
01716     def tell(self):
01717         if not self._seekable:
01718             raise UnsupportedOperation("underlying stream is not seekable")
01719         if not self._telling:
01720             raise IOError("telling position disabled by next() call")
01721         self.flush()
01722         position = self.buffer.tell()
01723         decoder = self._decoder
01724         if decoder is None or self._snapshot is None:
01725             if self._decoded_chars:
01726                 # This should never happen.
01727                 raise AssertionError("pending decoded text")
01728             return position
01729 
01730         # Skip backward to the snapshot point (see _read_chunk).
01731         dec_flags, next_input = self._snapshot
01732         position -= len(next_input)
01733 
01734         # How many decoded characters have been used up since the snapshot?
01735         chars_to_skip = self._decoded_chars_used
01736         if chars_to_skip == 0:
01737             # We haven't moved from the snapshot point.
01738             return self._pack_cookie(position, dec_flags)
01739 
01740         # Starting from the snapshot position, we will walk the decoder
01741         # forward until it gives us enough decoded characters.
01742         saved_state = decoder.getstate()
01743         try:
01744             # Note our initial start point.
01745             decoder.setstate((b'', dec_flags))
01746             start_pos = position
01747             start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
01748             need_eof = 0
01749 
01750             # Feed the decoder one byte at a time.  As we go, note the
01751             # nearest "safe start point" before the current location
01752             # (a point where the decoder has nothing buffered, so seek()
01753             # can safely start from there and advance to this location).
01754             next_byte = bytearray(1)
01755             for next_byte[0] in next_input:
01756                 bytes_fed += 1
01757                 chars_decoded += len(decoder.decode(next_byte))
01758                 dec_buffer, dec_flags = decoder.getstate()
01759                 if not dec_buffer and chars_decoded <= chars_to_skip:
01760                     # Decoder buffer is empty, so this is a safe start point.
01761                     start_pos += bytes_fed
01762                     chars_to_skip -= chars_decoded
01763                     start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
01764                 if chars_decoded >= chars_to_skip:
01765                     break
01766             else:
01767                 # We didn't get enough decoded data; signal EOF to get more.
01768                 chars_decoded += len(decoder.decode(b'', final=True))
01769                 need_eof = 1
01770                 if chars_decoded < chars_to_skip:
01771                     raise IOError("can't reconstruct logical file position")
01772 
01773             # The returned cookie corresponds to the last safe start point.
01774             return self._pack_cookie(
01775                 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
01776         finally:
01777             decoder.setstate(saved_state)

Here is the call graph for this function:

def _pyio.TextIOWrapper.truncate (   self,
  pos = None 
)
Truncate size to pos, where pos is an int.

Reimplemented from _pyio.TextIOBase.

Definition at line 1778 of file _pyio.py.

01778 
01779     def truncate(self, pos=None):
01780         self.flush()
01781         if pos is None:
01782             pos = self.tell()
01783         return self.buffer.truncate(pos)

Here is the call graph for this function:

Return a bool indicating whether object was opened for writing.

If False, write() and truncate() will raise UnsupportedOperation.

Reimplemented from _pyio.IOBase.

Definition at line 1576 of file _pyio.py.

01576 
01577     def writable(self):
01578         return self.buffer.writable()

def _pyio.TextIOWrapper.write (   self,
  s 
)
Write string s to stream and returning an int.

Reimplemented from _pyio.TextIOBase.

Definition at line 1602 of file _pyio.py.

01602 
01603     def write(self, s):
01604         'Write data, where s is a str'
01605         if self.closed:
01606             raise ValueError("write to closed file")
01607         if not isinstance(s, str):
01608             raise TypeError("can't write %s to text stream" %
01609                             s.__class__.__name__)
01610         length = len(s)
01611         haslf = (self._writetranslate or self._line_buffering) and "\n" in s
01612         if haslf and self._writetranslate and self._writenl != "\n":
01613             s = s.replace("\n", self._writenl)
01614         encoder = self._encoder or self._get_encoder()
01615         # XXX What if we were just reading?
01616         b = encoder.encode(s)
01617         self.buffer.write(b)
01618         if self._line_buffering and (haslf or "\r" in s):
01619             self.flush()
01620         self._snapshot = None
01621         if self._decoder:
01622             self._decoder.reset()
01623         return length

Here is the call graph for this function:

def _pyio.IOBase.writelines (   self,
  lines 
) [inherited]

Definition at line 514 of file _pyio.py.

00514 
00515     def writelines(self, lines):
00516         self._checkClosed()
00517         for line in lines:
00518             self.write(line)
00519 
00520 io.IOBase.register(IOBase)
00521 


Member Data Documentation

Definition at line 1503 of file _pyio.py.

int _pyio.TextIOWrapper._CHUNK_SIZE = 2048 [static, private]

Definition at line 1472 of file _pyio.py.

Definition at line 1514 of file _pyio.py.

Definition at line 1515 of file _pyio.py.

Definition at line 1513 of file _pyio.py.

Definition at line 1512 of file _pyio.py.

Definition at line 1505 of file _pyio.py.

Definition at line 1506 of file _pyio.py.

Definition at line 1518 of file _pyio.py.

Definition at line 1504 of file _pyio.py.

Definition at line 1509 of file _pyio.py.

Definition at line 1508 of file _pyio.py.

Definition at line 1507 of file _pyio.py.

Definition at line 1517 of file _pyio.py.

Definition at line 1516 of file _pyio.py.

Definition at line 1517 of file _pyio.py.

Definition at line 1511 of file _pyio.py.

Reimplemented in _pyio.StringIO.

Definition at line 1510 of file _pyio.py.


The documentation for this class was generated from the following file: