运行器 ¶
此节提纲了运行 asyncio 代码的高级 asyncio 原语。
它们的构建是基于 事件循环 旨在简化常见广泛零散情景下的 async 代码使用。
运行异步程序 ¶
- asyncio. run ( coro , * , debug = None , loop_factory = None ) ¶
-
执行 协程 coro 并返回结果。
此函数运行传递的协程,负责管理 asyncio 事件循环, 定稿异步生成器 , and closing the executor.
无法调用此函数,当另一 asyncio 事件循环在同一线程中运行时。
若 debug is
True,以调试模式运行事件循环。False明确禁用调试模式。None用于遵守全局 调试模式 设置。若 loop_factory 不是
None, it is used to create a new event loop; otherwiseasyncio.new_event_loop()is used. The loop is closed at the end. This function should be used as a main entry point for asyncio programs, and should ideally only be called once. It is recommended to use loop_factory to configure the event loop instead of policies. Passingasyncio.EventLoopallows running asyncio without the policy system.The executor is given a timeout duration of 5 minutes to shutdown. If the executor hasn’t finished within that duration, a warning is emitted and the executor is closed.
范例:
async def main(): await asyncio.sleep(1) print('hello') asyncio.run(main())