diff options
author | Guido van Rossum <guido@python.org> | 2007-05-21 23:13:11 (GMT) |
---|---|---|
committer | Guido van Rossum <guido@python.org> | 2007-05-21 23:13:11 (GMT) |
commit | 7d0a8264ff29fe8963bb1cc67debc03e7c728a98 (patch) | |
tree | bb50e8fb32745b01279619826cb5bb30f2ccac12 /Lib/io.py | |
parent | 88effc1251c295b0e70961b587fe0de63bf10754 (diff) | |
download | cpython-7d0a8264ff29fe8963bb1cc67debc03e7c728a98.zip cpython-7d0a8264ff29fe8963bb1cc67debc03e7c728a98.tar.gz cpython-7d0a8264ff29fe8963bb1cc67debc03e7c728a98.tar.bz2 |
Sockets facelift. APIs that could return binary data (e.g. aton() and
recv()) now return bytes, not str or str8. The socket.py code is
redone; it now subclasses _socket.socket and instead of having its own
_fileobject for makefile(), it uses io.SocketIO. Some stuff in io.py
was moved around to make this work. (I really need to rethink my
policy regarding readline() and read(-1) on raw files; and readline()
on buffered files ought to use peeking(). Later.)
Diffstat (limited to 'Lib/io.py')
-rw-r--r-- | Lib/io.py | 54 |
1 files changed, 37 insertions, 17 deletions
@@ -295,6 +295,22 @@ class IOBase: """ return False + ### Readline ### + + def readline(self, sizehint: int = -1) -> bytes: + """For backwards compatibility, a (slow) readline().""" + if sizehint is None: + sizehint = -1 + res = b"" + while sizehint < 0 or len(res) < sizehint: + b = self.read(1) + if not b: + break + res += b + if b == b"\n": + break + return res + class RawIOBase(IOBase): @@ -366,7 +382,6 @@ class SocketIO(RawIOBase): """Raw I/O implementation for stream sockets.""" # XXX More docs - # XXX Hook this up to socket.py def __init__(self, sock, mode): assert mode in ("r", "w", "rw") @@ -377,13 +392,32 @@ class SocketIO(RawIOBase): def readinto(self, b): return self._sock.recv_into(b) + def read(self, n: int = None) -> bytes: + """read(n: int) -> bytes. Read and return up to n bytes. + + Returns an empty bytes array on EOF, or None if the object is + set not to block and has no data to read. + """ + if n is None: + n = -1 + if n >= 0: + return RawIOBase.read(self, n) + # Support reading until the end. + # XXX Why doesn't RawIOBase support this? + data = b"" + while True: + more = RawIOBase.read(self, DEFAULT_BUFFER_SIZE) + if not more: + break + data += more + return data + def write(self, b): return self._sock.send(b) def close(self): if not self.closed: - RawIOBase.close() - self._sock.close() + RawIOBase.close(self) def readable(self): return "r" in self._mode @@ -450,20 +484,6 @@ class BufferedIOBase(IOBase): b[:n] = data return n - def readline(self, sizehint: int = -1) -> bytes: - """For backwards compatibility, a (slow) readline().""" - if sizehint is None: - sizehint = -1 - res = b"" - while sizehint < 0 or len(res) < sizehint: - b = self.read(1) - if not b: - break - res += b - if b == b"\n": - break - return res - def write(self, b: bytes) -> int: """write(b: bytes) -> int. Write the given buffer to the IO stream. |