在非异步函数中调用异步函数并获得返回值,可以使用 'asyncio.run()' 函数。以下是一个示例:

import asyncio

async def async_function():
    # 在这里编写你的异步函数逻辑
    return 'Hello, World!'

def sync_function():
    # 在这里调用异步函数并获得返回值
    result = asyncio.run(async_function())
    print(result)

sync_function()

在上述示例中,'async_function()' 是一个异步函数,它返回字符串 'Hello, World!'。'sync_function()' 是一个非异步函数,它调用 'asyncio.run()' 函数来运行异步函数,并获得返回值。最后,将返回值打印出来。

运行上述代码,输出结果为:'Hello, World!'。


原文地址: https://www.cveoy.top/t/topic/o3kr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录