API documentation#

asyncio#

The asyncio package, tracking PEP 3156.

class asyncio.AbstractEventLoop[源代码]#

Abstract event loop.

close()[源代码]#

Close the loop.

The loop should not be running.

This is idempotent and irreversible.

No other methods should be called after this one.

async connect_read_pipe(protocol_factory, pipe)[源代码]#

Register read pipe in event loop. Set the pipe to non-blocking mode.

protocol_factory should instantiate object with Protocol interface. pipe is a file-like object. Return pair (transport, protocol), where transport supports the ReadTransport interface.

async connect_write_pipe(protocol_factory, pipe)[源代码]#

Register write pipe in event loop.

protocol_factory should instantiate object with BaseProtocol interface. Pipe is file-like object already switched to nonblocking. Return pair (transport, protocol), where transport support WriteTransport interface.

async create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)[源代码]#

A coroutine which creates a datagram endpoint.

This method will try to establish the endpoint in the background. When successful, the coroutine returns a (transport, protocol) pair.

protocol_factory must be a callable returning a protocol instance.

socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on host (or family if specified), socket type SOCK_DGRAM.

reuse_address tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire. If not specified it will automatically be set to True on UNIX.

reuse_port tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows and some UNIX’s. If the SO_REUSEPORT constant is not defined then this capability is unsupported.

allow_broadcast tells the kernel to allow this endpoint to send messages to the broadcast address.

sock can optionally be specified in order to use a preexisting socket object.

async create_server(protocol_factory, host=None, port=None, *, family=AddressFamily.AF_UNSPEC, flags=AddressInfo.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True)[源代码]#

A coroutine which creates a TCP server bound to host and port.

The return value is a Server object which can be used to stop the service.

If host is an empty string or None all interfaces are assumed and a list of multiple sockets will be returned (most likely one for IPv4 and another one for IPv6). The host parameter can also be a sequence (e.g. list) of hosts to bind to.

family can be set to either AF_INET or AF_INET6 to force the socket to use IPv4 or IPv6. If not set it will be determined from host (defaults to AF_UNSPEC).

flags is a bitmask for getaddrinfo().

sock can optionally be specified in order to use a preexisting socket object.

backlog is the maximum number of queued connections passed to listen() (defaults to 100).

ssl can be set to an SSLContext to enable SSL over the accepted connections.

reuse_address tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire. If not specified will automatically be set to True on UNIX.

reuse_port tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows.

ssl_handshake_timeout is the time in seconds that an SSL server will wait for completion of the SSL handshake before aborting the connection. Default is 60s.

start_serving set to True (default) causes the created server to start accepting connections immediately. When set to False, the user should await Server.start_serving() or Server.serve_forever() to make the server to start accepting connections.

async create_unix_server(protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)[源代码]#

A coroutine which creates a UNIX Domain Socket server.

The return value is a Server object, which can be used to stop the service.

path is a str, representing a file system path to bind the server socket to.

sock can optionally be specified in order to use a preexisting socket object.

backlog is the maximum number of queued connections passed to listen() (defaults to 100).

ssl can be set to an SSLContext to enable SSL over the accepted connections.

ssl_handshake_timeout is the time in seconds that an SSL server will wait for the SSL handshake to complete (defaults to 60s).

start_serving set to True (default) causes the created server to start accepting connections immediately. When set to False, the user should await Server.start_serving() or Server.serve_forever() to make the server to start accepting connections.

is_closed()[源代码]#

Returns True if the event loop was closed.

is_running()[源代码]#

Return whether the event loop is currently running.

run_forever()[源代码]#

Run the event loop until stop() is called.

run_until_complete(future)[源代码]#

Run the event loop until a Future is done.

Return the Future’s result, or raise its exception.

async sendfile(transport, file, offset=0, count=None, *, fallback=True)[源代码]#

Send a file through a transport.

Return an amount of sent bytes.

async shutdown_asyncgens()[源代码]#

Shutdown all active asynchronous generators.

async shutdown_default_executor()[源代码]#

Schedule the shutdown of the default executor.

async start_tls(transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None)[源代码]#

Upgrade a transport to TLS.

Return a new transport that protocol should start using immediately.

stop()[源代码]#

Stop the event loop as soon as reasonable.

Exactly how soon that is may depend on the implementation, but no more I/O callbacks should be scheduled.

asyncio.gather(*coros_or_futures, loop=None, return_exceptions=False)[源代码]#

Return a future aggregating results from the given coroutines/futures.

Coroutines will be wrapped in a future and scheduled in the event loop. They will not necessarily be scheduled in the same order as passed in.

All futures must share the same event loop. If all the tasks are done successfully, the returned future’s result is the list of results (in the order of the original sequence, not necessarily the order of results arrival). If return_exceptions is True, exceptions in the tasks are treated the same as successful results, and gathered in the result list; otherwise, the first raised exception will be immediately propagated to the returned future.

Cancellation: if the outer Future is cancelled, all children (that have not completed yet) are also cancelled. If any child is cancelled, this is treated as if it raised CancelledError – the outer Future is not cancelled in this case. (This is to prevent the cancellation of one child to cause other children to be cancelled.)

If return_exceptions is False, cancelling gather() after it has been marked done won’t cancel any submitted awaitables. For instance, gather can be marked done after propagating an exception to the caller, therefore, calling gather.cancel() after catching an exception (raised by one of the awaitables) from gather won’t cancel any other awaitables.

asyncio.run(main, *, debug=None)[源代码]#

Execute the coroutine and return the result.

This function runs the passed coroutine, taking care of managing the asyncio event loop and finalizing asynchronous generators.

This function cannot be called when another asyncio event loop is running in the same thread.

If debug is True, the event loop will be run in debug mode.

This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once.

Example:

async def main():

await asyncio.sleep(1) print(‘hello’)

asyncio.run(main())