stream_reader

Closing a connection

  • Application code should not call reader.close(). To gracefully close a connection, call writer.close() and, if needed, await writer.wait_closed(). The protocol will signal end-of-input to the reader.

  • The protocol layer calls reader.feed_eof() when the underlying transport indicates EOF (for example in connection_lost()). This marks the reader as EOF and wakes any pending read coroutines.

  • After feed_eof(), subsequent read() calls will drain any buffered bytes and then return b""; readline()/iteration will stop at EOF. Use reader.at_eof() to test EOF state.

Example (application code):

async def app(reader, writer):
    # ... use reader/readline/readuntil ...
    writer.close()
    await writer.wait_closed()
    # reader will eventually see EOF; reads return b"" once buffer drains

Example (protocol integration):

class MyProtocol(asyncio.Protocol):
    def __init__(self, reader):
        self.reader = reader
    def connection_lost(self, exc):
        if exc:
            self.reader.set_exception(exc)
        self.reader.feed_eof()

Deprecation notes:

  • TelnetReader.close() is deprecated; use feed_eof() (protocol) and writer.close()/wait_closed() (application).

  • TelnetReader.connection_closed property is deprecated; use reader.at_eof().

Module provides class TelnetReader and TelnetReaderUnicode.

class TelnetReader(limit=65536)[source]

Telnet protocol stream reader.

A copy of asyncio.StreamReader with telnet-aware readline().

Initialize TelnetReader with optional buffer size limit.

exception()[source]

Return the exception if set, otherwise None.

Return type:

Optional[Exception]

set_exception(exc)[source]

Set the exception and wake up any waiting coroutine.

Return type:

None

set_transport(transport)[source]

Set the transport for flow control.

Return type:

None

feed_eof()[source]

Mark EOF on the reader and wake any pending readers.

This should be called by the Telnet protocol when the underlying transport indicates end-of- input (e.g., in connection_lost()). It sets the internal EOF flag and wakes any read coroutines waiting for more data.

Application code typically should not call this method directly. To gracefully close a connection from application code, call writer.close() and await writer.wait_closed(). The protocol will eventually call feed_eof() on the reader as part of shutdown.

After feed_eof(), read() will drain remaining buffered bytes and then return b””; readline()/iteration will stop at EOF.

Return type:

None

at_eof()[source]

Return True if the buffer is empty and ‘feed_eof’ was called.

Return type:

bool

feed_data(data)[source]

Feed data bytes to the reader buffer.

Return type:

None

async readuntil(separator=b'\\n')[source]

Read data from the stream until separator is found.

On success, the data and separator will be removed from the internal buffer (consumed). Returned data will include the separator at the end.

Configured stream limit is used to check result. Limit sets the maximal length of data that can be returned, not counting the separator.

If an EOF occurs and the complete separator is still not found, an IncompleteReadError exception will be raised, and the internal buffer will be reset. The IncompleteReadError.partial attribute may contain the separator partially.

If the data cannot be read because of over limit, a LimitOverrunError exception will be raised, and the data will be left in the internal buffer, so it can be read again.

Raises:
Return type:

bytes

async readuntil_pattern(pattern)[source]

Read data from the stream until pattern is found.

On success, the data and pattern will be removed from the internal buffer (consumed). Returned data will include the pattern at the end.

Configured stream limit is used to check result. Limit sets the maximal length of data that can be returned, not counting the pattern.

If an EOF occurs and the complete pattern is still not found, an IncompleteReadError exception will be raised, and the internal buffer will be reset. The IncompleteReadError.partial attribute may contain the pattern partially.

If the data cannot be read because of over limit, a LimitOverrunError exception will be raised, and the data will be left in the internal buffer, so it can be read again.

Raises:
Return type:

bytes

async read(n=-1)[source]

Read up to n bytes from the stream.

If n is not provided, or set to -1, read until EOF and return all read bytes. If the EOF was received and the internal buffer is empty, return an empty bytes object.

If n is zero, return empty bytes object immediately.

If n is positive, this function try to read n bytes, and may return less or equal bytes than requested, but at least one byte. If EOF was received before any byte is read, this function returns empty byte object.

Returned value is not limited with limit, configured at stream creation.

If stream was paused, this function will automatically resume it if needed.

Return type:

bytes

async readexactly(n)[source]

Read exactly n bytes.

Raise an IncompleteReadError if EOF is reached before n bytes can be read. The IncompleteReadError.partial attribute of the exception will contain the partial read bytes.

if n is zero, return empty bytes object.

Returned value is not limited with limit, configured at stream creation.

If stream was paused, this function will automatically resume it if needed.

Raises:
Return type:

bytes

property connection_closed: bool

Deprecated: use at_eof() instead.

close()[source]

Deprecated: use feed_eof() instead.

TelnetReader.close() existed briefly and is deprecated. Protocol implementations should call feed_eof() to signal end-of-input. Application code should not close the reader directly; instead, call writer.close() and await writer.wait_closed() to initiate a graceful shutdown.

Return type:

None

async readline()[source]

Read one line.

Where “line” is a sequence of characters ending with CR LF, LF, or CR NUL. This readline function is a strict interpretation of Telnet Protocol RFC 854.

The sequence “CR LF” must be treated as a single “new line” character and used whenever their combined action is intended; The sequence “CR NUL” must be used where a carriage return alone is actually desired; and the CR character must be avoided in other contexts.

And therefore, a line does not yield for a stream containing a CR if it is not succeeded by NUL or LF.

Given a stream containing the following sequences, readline() yields:

  • \\r\\x00 – yields at \\r

  • \\r\\n – yields at \\r\\n

  • \\n – yields at \\n

  • \\r – yields at \\r

If EOF is received before the termination of a line, the method will yield the partially read string.

Return type:

bytes

class TelnetReaderUnicode(fn_encoding, *, limit=65536, encoding_errors='replace')[source]

Unicode-decoding Telnet stream reader.

Extends TelnetReader to provide automatic decoding of bytes to unicode strings using a configurable encoding determined by callback function.

A Unicode StreamReader interface for Telnet protocol.

Parameters:

fn_encoding (Callable[..., str]) – Function callback, receiving boolean keyword argument incoming=True, which is used by the callback to determine what encoding should be used to decode the value in the direction specified.

decode(buf, final=False)[source]

Decode bytes buf using preferred encoding.

Return type:

str

async readline()[source]

Read one line.

See ancestor method, readline() for details.

Return type:

str

async read(n=-1)[source]

Read up to n bytes.

If the EOF was received and the internal buffer is empty, return an empty string.

Parameters:

n (int) – If n is not provided, or set to -1, read until EOF and return all characters as one large string.

Return type:

str

async readexactly(n)[source]

Read exactly n unicode characters.

Raises:

asyncio.IncompleteReadError – if the end of the stream is reached before n can be read. The asyncio.IncompleteReadError.partial attribute of the exception contains the partial read characters.

Return type:

str