Asynchronous IO (async IO) is an asynchronous programming design and is supported in Python's asyncio
module and canUse the two definition keywords async
/await
to define coroutines, and pass asyncio
Provides the foundation and API for running and managing coroutines.
In general, most programming languages have methods that follow a so-called "subroutine" calling model.In this model, each call to a function is called execution, moves to the beginning of the function, and continues until the end of the function (or return
statement) is reached, at which point execution moves immediately toThe point after the function is called, any subsequent calls to that function are independent, and that call will start again at the beginning.
However, there is an alternative code execution model called the coroutine invocation model.In this calling model, the method (called a coroutine ) that will execute back to the caller has a new method: instead of returning it can "yield" control.When a coroutine's "yields" execution moves back to the point immediately after being called, but future calls to the coroutine don't start again at the beginning, instead they continue from the most recently stopped execution.
This way control can be executed back and forth between the calling code and the coroutine
code, as shown below:
import asyncioimport timeasync def main(): print(f'{time.ctime()} Hello!') await asyncio.sleep(1.0) print(f'{time.ctime()} See you again!')asyncio.run(main())
Run result:
$ python asynciodemo.py Sat Jul 9 23:19:40 2022 Hello!Sat Jul 9 23:19:41 2022 See you again!
asyncio
provides a run()
function to execute the async def
function and then all other coroutines called from there like
Reference link:
Async IO in Python: A Complete Walkthrough