The asyncio module in Python allows you to write single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources, running network clients and servers, and other related primitives. The module was introduced in Python 3.4.
Here’s an example of how you might use asyncio:
```
import asyncio
async def hello_world(): print(“Hello, World!”) await asyncio.sleep(3) print(“Goodbye, World!”)
In this simple script:
- the hello\_world function is defined with the async keyword, which means it’s an asyncio coroutine function.
- inside the hello\_world function, we print “Hello, World!”, then use the await keyword with asyncio.sleep(3), which is also a coroutine and does exactly what you’d expect: it sleeps for 3 seconds.
- then we print “Goodbye, World!”.
- outside of the coroutine, we get the event loop, run our hello\_world coroutine until it completes, and then close the loop.
This script will print “Hello, World!”, wait for three seconds, and print “Goodbye, World!”.
Here is another example to demonstrate how asyncio can handle multiple tasks concurrently:
```
import asyncio
async def print_after(delay, msg): await asyncio.sleep(delay) print(msg)
async def main(): task1 = asyncio.create_task(print_after(1, ‘one second delay’)) task2 = asyncio.create_task(print_after(2, ‘two seconds delay’))
await task1 await task2In this script:
- We’ve created two tasks that will be executed concurrently. Task one will sleep for one second, then print ‘one second delay’. Task two will sleep for two seconds, then print ‘two seconds delay’.
- We then tell asyncio to run both tasks by using await on each task within the main coroutine.
- If you’re using Python 3.7+ you can use asyncio.run() to execute async def functions, instead of manually getting and closing the loop.
Asyncio is a powerful library for managing multiple I/O-bound tasks concurrently and is well worth knowing if you’re dealing with network programming, web scraping, or other I/O-bound tasks in Python.