asyncio — asynchronous I/O scheduler
This module provides a cooperative-multitasking scheduler for async/await
coroutines, along with primitives for synchronisation (locks, events) and
non-blocking TCP networking via stream readers and writers. Tasks are run
concurrently on a single event loop; the currently running task yields control
back to the loop with await.
Example:
import asyncio
async def blink(led, period_ms):
while True:
led.on()
await asyncio.sleep_ms(5)
led.off()
await asyncio.sleep_ms(period_ms)
async def main(led1, led2):
asyncio.create_task(blink(led1, 700))
asyncio.create_task(blink(led2, 400))
await asyncio.sleep_ms(10_000)
# Running on a pyboard
from pyb import LED
asyncio.run(main(LED(1), LED(2)))
# Running on a generic board
from machine import Pin
asyncio.run(main(Pin(1), Pin(2)))
Core functions
- asyncio.create_task(coro: Coroutine) Task
Create a new task from the given coroutine and schedule it to run.
Returns the corresponding
Taskobject.
- asyncio.run(coro: Coroutine) Any
Create a new task from the given coroutine and run it until it completes.
Returns the value returned by coro.
Additional functions
- asyncio.wait_for(awaitable: Awaitable, timeout: float) Any
Wait for the awaitable to complete, but cancel it if it takes longer than timeout seconds. If awaitable is not a task then a task will be created from it.
If a timeout occurs, it cancels the task and raises
asyncio.TimeoutError: this should be trapped by the caller. The task receivesasyncio.CancelledErrorwhich may be ignored or trapped usingtry...exceptortry...finallyto run cleanup code.Returns the return value of awaitable.
This is a coroutine.
class Task
- class asyncio.Task
This object wraps a coroutine into a running task. Tasks can be waited on using
await task, which will wait for the task to complete and return the return value of the task.Tasks should not be created directly, rather use
create_taskto create them.
class Event
- class asyncio.Event
Create a new event which can be used to synchronise tasks. Events start in the cleared state.
- set() None
Set the event. Any tasks waiting on the event will be scheduled to run.
Note: This must be called from within a task. It is not safe to call this from an IRQ, scheduler callback, or other thread. See
ThreadSafeFlag.
class ThreadSafeFlag
- class asyncio.ThreadSafeFlag
Create a new flag which can be used to synchronise a task with code running outside the asyncio loop, such as other threads, IRQs, or scheduler callbacks. Flags start in the cleared state.
class Lock
- class asyncio.Lock
Create a new lock which can be used to coordinate tasks. Locks start in the unlocked state.
In addition to the methods below, locks can be used in an
async withstatement.
TCP stream connections
- asyncio.open_connection(host: str, port: int, ssl: ssl.SSLContext | bool | None = None) Tuple[Stream, Stream]
Open a TCP connection to the given host and port. The host address will be resolved using
socket.getaddrinfo, which is currently a blocking call. If ssl is assl.SSLContextobject, this context is used to create the transport; if ssl isTrue, a default context is used.Returns a pair of streams: a reader and a writer stream. Will raise a socket-specific
OSErrorif the host could not be resolved or if the connection could not be made.This is a coroutine.
- asyncio.start_server(callback: Callable, host: str, port: int, backlog: int = 5, ssl: ssl.SSLContext | None = None) Server
Start a TCP server on the given host and port. The callback will be called with incoming, accepted connections, and be passed 2 arguments: reader and writer streams for the connection.
If ssl is a
ssl.SSLContextobject, this context is used to create the transport.Returns a
Serverobject.This is a coroutine.
- class asyncio.Stream
This represents a TCP stream connection. To minimise code this class implements both a reader and a writer, and both
StreamReaderandStreamWriteralias to this class.- get_extra_info(v: str) Any
Get extra information about the stream, given by v. The valid values for v are:
peername.
- read(n: int = -1) bytes
Read up to n bytes and return them. If n is not provided or -1 then read all bytes until EOF. The returned value will be an empty bytes object if EOF is encountered before any bytes are read.
This is a coroutine.
- readinto(buf: bytearray | memoryview) int
Read up to n bytes into buf with n being equal to the length of buf.
Return the number of bytes read into buf.
This is a coroutine, and a MicroPython extension.
- readexactly(n: int) bytes
Read exactly n bytes and return them as a bytes object.
Raises an
EOFErrorexception if the stream ends before reading n bytes.This is a coroutine.
- write(buf: bytes) None
Accumulated buf to the output buffer. The data is only flushed when
Stream.drainis called. It is recommended to callStream.drainimmediately after calling this function.
Event Loop
- asyncio.new_event_loop() Loop
Reset the event loop and return it.
Note: since MicroPython only has a single event loop this function just resets the loop’s state, it does not create a new one.
- class asyncio.Loop
This represents the object which schedules and runs tasks. It cannot be created, use
get_event_loopinstead.- create_task(coro: Coroutine) Task
Create a task from the given coro and return the new
Taskobject.
- run_until_complete(awaitable: Awaitable) Any
Run the given awaitable until it completes. If awaitable is not a task then it will be promoted to one.
- set_exception_handler(handler: Callable) None
Set the exception handler to call when a Task raises an exception that is not caught. The handler should accept two arguments:
(loop, context).