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

Asyncio问题:如何解决‘a coroutine was expected’错误?

解决 "a coroutine was expected, got <_GatheringFuture pending>" 错误

这个错误的核心原因是你传给asyncio.run()的不是协程对象,而是asyncio.gather()返回的Future对象,asyncio.run()要求必须传入一个协程作为参数。

以下是具体修复步骤:

  • 检查代码的入口逻辑,确保你通过顶层协程包裹asyncio.gather()调用,而非直接将gather的结果传给asyncio.run()。

    错误写法示例:

    if __name__ == "__main__":
        # 错误:直接传递gather返回的Future对象
        asyncio.run(asyncio.gather(
            connect_to_device("F0CBEBD3-299B-4139-A9FC-44618C720157"),
            connect_to_device("另一个设备UUID")
        ))
    

    正确写法(与bleak官方示例逻辑一致):

    async def main():
        await asyncio.gather(
            connect_to_device("F0CBEBD3-299B-4139-A9FC-44618C720157"),
            connect_to_device("另一个设备UUID")
        )
    
    if __name__ == "__main__":
        # 传入协程对象main()给run方法
        asyncio.run(main())
    
  • 确认connect_to_device函数是用async def定义的协程函数,只有协程才能被asyncio.gather()正确收集执行。

如果代码和官方示例完全一致仍报错,检查Python版本:asyncio.run()仅支持Python 3.7及以上版本,若版本过低,可升级Python,或改用asyncio.get_event_loop().run_until_complete(main())替代asyncio.run(main())。

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:33:16