Python 3.8.13中异步函数无法运行问题求助
代码修复方案
原代码存在的问题及修复点:
- 函数定义语法错误:
async def_1()和async def_2(number)中,def是关键字,必须和函数名之间加空格,正确写法是async def def_1()和async def def_2(number)。 globals是内置函数,需调用globals()获取全局命名空间字典,不能直接用globals[...],要改成globals()['example_{}'.format(i)]。asyncio.run()需要接收协程对象,直接传def_2是函数对象,必须调用函数并传入参数(比如def_2(5)),才能得到协程对象。- 仅存储协程对象不会执行异步逻辑,若要批量运行
def_1的协程,需用asyncio.gather()收集并等待所有协程完成。
修复后的完整代码:
import asyncio async def def_1(): print(f"协程 def_1 运行中") # 可添加实际异步操作,比如等待1秒模拟任务 # await asyncio.sleep(1) async def def_2(number): coros = [] for i in range(number): coro = def_1() globals()['example_{}'.format(i)] = coro coros.append(coro) # 异步运行所有收集到的协程 await asyncio.gather(*coros) # 调用def_2并传入参数,示例创建3个协程 asyncio.run(def_2(3))
说明:
- 修正函数定义语法后,异步函数可以被正常识别。
- 通过
globals()正确将协程对象存入全局变量。 asyncio.gather()会并发运行所有传入的协程,实现真正的异步执行。asyncio.run(def_2(3))正确传入协程对象,启动异步事件循环执行任务。
内容的提问来源于stack exchange,提问作者Kim
相关产品推荐
相关产品推荐

