Skip to content
鼓励作者:欢迎打赏犒劳

python的异步

async

注意: `wait` 只能在 `async def` 的函数里面用,而 `async def` 的函数必须用 `asyncio.run()` 来启动。

python
import asyncio


# 定义一个异步函数
async def async_func():
    await asyncio.sleep(1)  # 模拟异步操作
    return "Hello"

# ✅ 正确:在 async 函数中使用 await
async def correct():
    result = await async_func()  # 正确
    return result

# ✅ 运行异步函数的正确方式
if __name__ == "__main__":
    # 方式1:用 asyncio.run() 运行
    result = asyncio.run(async_func())
    print(result)  # 输出: Hello

    # 方式2:在 async 函数中用 await 调用另一个 async 函数
    result2 = asyncio.run(correct())
    print(result2)  # 输出: Hello

如有转载或 CV 的请标注本站原文地址