You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:36:22