异步asyncio
asyncio是一个使用async / await语法编写并发代码的库。
asyncio用作多个Python异步框架的基础,这些框架提供高性能的网络和Web服务器,数据库连接库,分布式任务队列等。
asyncio通常非常适合IO绑定和高级 结构化网络代码。
asyncio提供了一组高级 API:
- 同时运行Python协同程序并完全控制它们的执行;
- 执行网络IO和IPC ;
- 控制子过程 ;
- 通过队列分配任务;
- 同步并发代码;
此外,还有一些用于库和框架开发人员的低级 API :
-
创建和管理事件循环,提供异步API
networking,运行subprocesses,处理等;OS signals - 使用传输实现有效的协议 ;
- 使用async / await语法桥接基于回调的库和代码。
Conroutines
使用async / await语法声明的协同程序是编写asyncio应用程序的首选方法。例如,以下代码片段(需要Python 3.7+)打印“hello”,等待1秒,然后打印“world”:
import asyncio
async def main():
print('hello')
await asyncio.sleep(1)
print('world')
asyncio.run(main())
# hello
# world
上面代码等同于下面(不推荐使用基于生成器的协同程序的支持,并计划在Python 3.10中删除。)
import asyncio
@asyncio.coroutine
def main():
print('hello')
yield from asyncio.sleep(1)
print('world')
asyncio.run(main())
asyncio实际等同于下面的工作(参数为An asyncio.Future, a coroutine or an awaitable is required)
import asyncio
@asyncio.coroutine
def main():
print('hello')
yield from asyncio.sleep(1)
print('world')
# asyncio.run(main())
loop = asyncio.events.new_event_loop()
asyncio.events.set_event_loop(loop)
loop.run_until_complete(main())
# hello
# world
1 This function runs the passed coroutine, taking care of 2 managing the asyncio event loop and finalizing asynchronous 3 generators. 4 5 This function cannot be called when another asyncio event loop is 6 running in the same thread. 7 8 If debug is True, the event loop will be run in debug mode. 9 10 This function always creates a new event loop and closes it at the end. 11 It should be used as a main entry point for asyncio programs, and should 12 ideally only be called once.