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

如何在Python同步方法中调用异步方法并等待其执行完成?

解决同步方法中阻塞等待异步方法执行完成的问题

要在同步方法中调用异步方法并等待其完成后再返回,不让异步任务在后台执行,可以通过获取当前运行的事件循环,调用其run_until_complete方法实现,具体修改如下:

修改后的完整代码

#!/usr/bin/env python3

import asyncio

class SomeInterface():
    def some_method(self, s):
        pass

class MyImpl(SomeInterface):
    def __init__(self, helper_async_obj):
        self.helper = helper_async_obj

    def some_method(self, s):
        print("before using async helper")
        # 获取当前运行的事件循环,阻塞等待异步协程执行完成
        loop = asyncio.get_running_loop()
        loop.run_until_complete(self.helper.f(s))
        print("after async helper is done")

class AsyncHelper():
    async def f(self, s):
        print(f"before sleep: {s}")
        await asyncio.sleep(1)
        print(f"after sleep: {s}")

async def main():
    ah = AsyncHelper()
    my_impl = MyImpl(ah)
    my_impl.some_method("hello")
    # 保持事件循环运行
    await asyncio.get_running_loop().create_future()

if __name__ == "__main__":
    asyncio.run(main())

原理说明

  • 你的代码已经处于一个运行中的事件循环(main是异步函数,被asyncio.run启动),此时不能用asyncio.run(它会尝试创建新事件循环,引发冲突报错)。
  • asyncio.get_running_loop()获取当前活跃的事件循环,run_until_complete会阻塞当前线程,直到传入的异步协程执行完毕,完全满足“等待异步方法完成后再返回同步方法”的需求。

执行结果

运行代码后输出与期望一致:

before using async helper
before sleep: hello
after sleep: hello
after async helper is done

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:01:20