Python Glossary Русский

Python 3.4+Async programmingterm

asyncio.StreamWriter

streams

The writing half of an asynchronous connection: write() puts bytes into a buffer, drain() waits for the buffer to empty, close() and wait_closed() shut the connection.

Syntax

writer.write(data); await writer.drain(); writer.close(); await writer.wait_closed()

write() is a plain method, not a coroutine: it sends nothing right away but accumulates bytes, and without await writer.drain() a fast writer bloats memory. It accepts only bytes — encode strings first, otherwise TypeError. close() does not wait either: to really close the connection follow it with await writer.wait_closed().

Examples

import asyncio
import socket
async def main():
    left, right = socket.socketpair()
    reader, writer = await asyncio.open_connection(sock=left)
    writer.write('привет\n'.encode())
    await writer.drain()
    await asyncio.sleep(0.01)
    print(right.recv(100).decode())  # → привет
    try:
        writer.write('строка')
    except TypeError:
        print('нужны bytes')  # → нужны bytes
    writer.close()
    await writer.wait_closed()
    right.close()
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy