Python Asyncio Module
asyncio is a library to write concurrent code using the async/await syntax. It is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.
Importing the Module
import asyncio
Basic Usage
Defining a Coroutine
A coroutine is declared with async def.
import asyncio
async def main():
print('Hello')
await asyncio.sleep(1)
print('...World!')
# Running the top-level entry point
# asyncio.run(main())
Running Concurrent Tasks
Use asyncio.gather() to run multiple coroutines concurrently.
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await asyncio.gather(
say_after(1, 'hello'),
say_after(2, 'world')
)
print(f"finished at {time.strftime('%X')}")
if __name__ == "__main__":
asyncio.run(main())
Timeouts
You can set a timeout for a coroutine using asyncio.wait_for().
try:
await asyncio.wait_for(eternity(), timeout=1.0)
except asyncio.TimeoutError:
print('timeout!')