stream_reader
Closing a connection
Application code should not call
reader.close(). To gracefully close a connection, callwriter.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 inconnection_lost()). This marks the reader as EOF and wakes any pending read coroutines.After
feed_eof(), subsequentread()calls will drain any buffered bytes and then returnb"";readline()/iteration will stop at EOF. Usereader.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; usefeed_eof()(protocol) andwriter.close()/wait_closed()(application).TelnetReader.connection_closedproperty is deprecated; usereader.at_eof().
Module provides class TelnetReader and TelnetReaderUnicode.
- class TelnetReader(limit=65536)[source]
Telnet protocol stream reader.
A copy of
asyncio.StreamReaderwith telnet-aware readline().Initialize TelnetReader with optional buffer size limit.
- 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:
- async readuntil(separator=b'\\n')[source]
Read data from the stream until
separatoris 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:
ValueError – If separator is empty.
asyncio.LimitOverrunError – If separator is not found and buffer exceeds limit.
asyncio.IncompleteReadError – If EOF is reached before separator is found.
- Return type:
- async readuntil_pattern(pattern)[source]
Read data from the stream until
patternis 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:
ValueError – If pattern is None, not a re.Pattern, or not a bytes pattern.
asyncio.LimitOverrunError – If pattern is not found and buffer exceeds limit.
asyncio.IncompleteReadError – If EOF is reached before pattern is found.
- Return type:
- 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:
- 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:
ValueError – If n is negative.
asyncio.IncompleteReadError – If EOF is reached before n bytes are read.
- Return type:
- 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:
- 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:
- 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 argumentincoming=True, which is used by the callback to determine what encoding should be used to decode the value in the direction specified.
- async readline()[source]
Read one line.
See ancestor method,
readline()for details.- Return type:
- 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.
- 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.partialattribute of the exception contains the partial read characters.- Return type: