Python Glossary Русский

Python 3.4+Linux · macOSAsync programmingfunction

asyncio.open_unix_connection()

streams

Connects to a Unix domain socket by file-system path and returns a (StreamReader, StreamWriter) pair.

Syntax

reader, writer = await asyncio.open_unix_connection(path=None, *, limit=2**16, **kwds)

Works like open_connection, but takes a socket file path instead of host and port; this is how you talk to local services such as Docker or PostgreSQL. The path is limited to about 107 bytes and a long absolute path raises OSError; a relative path is resolved from the current directory. A missing file raises FileNotFoundError, and nobody listening gives ConnectionRefusedError. Available on Linux and macOS only: asyncio has no Unix sockets on Windows.

Examples

import asyncio
async def main():
    try:
        await asyncio.open_unix_connection('нет-такого.sock')
    except FileNotFoundError:
        print('сокета нет')  # → сокета нет
asyncio.run(main())
import asyncio
async def hello(reader, writer):
    writer.write(b'hi')
    await writer.drain()
    writer.close()
async def main():
    async with await asyncio.start_unix_server(hello, 'demo.sock'):
        reader, writer = await asyncio.open_unix_connection('demo.sock')
        print(await reader.read())  # → b'hi'
        writer.close()
        await writer.wait_closed()
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy