Python Glossary Русский

Python 3.4+Async programmingterm

asyncio.StreamReader

streams

The reading half of an asynchronous connection: read(), readline(), readexactly(), readuntil(). asyncio.open_connection() and start_server() return it.

Syntax

reader, writer = await asyncio.open_connection(host, port); line = await reader.readline()

read(n) returns up to n bytes — whatever has arrived, not exactly n; readexactly(n) gives exactly n and raises IncompleteReadError if the stream ends early. read() with no argument waits for end of stream, not end of line, and can hang forever on a live connection. readline() keeps the trailing b'\n' and returns b'' at EOF without an error. You never build a StreamReader() by hand.

Examples

import asyncio
import socket
async def main():
    left, right = socket.socketpair()  # локальная пара сокетов вместо сети
    reader, writer = await asyncio.open_connection(sock=left)
    right.sendall(b'first\nsecond\n')
    right.close()
    print(await reader.readline())  # → b'first\n'
    print(await reader.readline())  # → b'second\n'
    print(await reader.readline(), reader.at_eof())  # → b'' True
    writer.close()
    await writer.wait_closed()
    await asyncio.sleep(0.01)
asyncio.run(main())
import asyncio
import socket
async def main():
    left, right = socket.socketpair()
    reader, writer = await asyncio.open_connection(sock=left)
    right.sendall(b'abc')
    right.close()
    try:
        await reader.readexactly(5)
    except asyncio.IncompleteReadError as e:
        print(e.partial)  # → b'abc'
    writer.close()
    await asyncio.sleep(0.01)
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy