Escribe para buscar…

AnyIO

AnyIO lets you write asynchronous code in Python that works with different async backends.

Esta página todavía no se ha traducido — se muestra en su idioma original:English

Introduction

AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio or Trio. It implements Trio-like structured concurrency (SC) on top of asyncio and works in harmony with the native SC of Trio itself.

ps
uv init anyio-basic
cd anyio-basic
uv add anyio

Basic Usage

Let’s create a simple example.

Make a file called task.py and add this code:

python
src/task.py
import anyio

async def do_task():
    print("Start ... ", end="")
    await anyio.sleep(2)
    print("end!")


async def main():
    await do_task()

if __name__ == "__main__":
    anyio.run(main)

When working with async code you normally use async and await keywords.

The main rules are that:

  • You can only use await inside async functions.
  • To call an async function, you need to use await in front of it.

In this case, we can use await inside of main() because it is an async function.

Call Async Functions

The function do_task() also needs to be declared with async def for us to be able to await for its result when calling it.

do_task() could be talking to a database, calling an API, or something else that needs to wait for something.

For this example, we simulate that by making do_task() wait there for 2 seconds:

python
src/task.py
async def do_task():
    print("Start ... ", end="")
    await anyio.sleep(2)
    print("end!")

Run the main function

As main() is an async function, we can’t call it directly because we can’t await it.

Instead, we call it with anyio.run():

python
src/task.py
if __name__ == "__main__":
    anyio.run(main)

Estás leyendo una vista previa.

Inicia sesión con Google para leer la página completa. Una cuenta de Google incluye 5 páginas gratuitas en total; el alumnado y el profesorado leen las páginas de su curso sin límite.

Iniciar sesión