Python Await 关键字详解:异步函数的暂停与执行
在 Python 中,'await' 是用于暂停一个异步函数的执行,等待一个异步操作完成,并返回异步操作的结果。'await' 关键字只能在异步函数内部使用。
以下是一个示例,展示了 'await' 的用法:
import asyncio
async def my_async_function():
print('Started')
await asyncio.sleep(2) # 模拟一个耗时的异步操作
print('Finished')
async def main():
print('Before await')
await my_async_function()
print('After await')
asyncio.run(main())
在上述示例中,我们定义了一个异步函数 my_async_function,其中使用了 'await' 关键字来暂停函数的执行,等待一个异步操作完成。在 my_async_function 中,我们使用 asyncio.sleep(2) 来模拟一个耗时的异步操作。
在 main 函数中,我们使用 'await' 关键字来等待 my_async_function 的执行完成。在 'await' 的位置,程序将暂停执行,直到 my_async_function 完成。
通过 asyncio.run(main()) 来执行 main 函数。
运行上述示例,输出如下:
Before await
Started
Finished
After await
可以看到,在 main 函数中使用 'await' 关键字等待 my_async_function 执行完成后,才会继续执行下一行代码。
需要注意的是,'await' 关键字只能在异步函数内部使用,而且异步函数必须由 'async' 关键字进行修饰。同时,'await' 后面的表达式必须是一个异步对象,如异步函数、异步生成器等。
原文地址: https://www.cveoy.top/t/topic/P2G 著作权归作者所有。请勿转载和采集!