- 与 with 中的上下文管理器需要定义两个方法 enter() 和 exit() 一样,异步上下文管理器同样也需要实现 aenter() 和 aexit() 方法。
- async with 异步上下文管理器同样只能在 协程函数 中使用,否则会报语法错误 ( SyntaxError )。
- 与普通上下文管理器相比,异步上下文管理器能够在其进入 enter() 和退出方法 exit() 中暂停执行。
- 详细的理解可参照普通的的with上下文管理器:
Python深入02 上下文管理器
示例代码
import asyncio
async def log(some_thing):
print(some_thing)
class AsyncContextManager:
async def __aenter__(self):
await log('entering context')
return "返回值做为c的值"
async def __aexit__(self, exc_type, exc, tb):
await log('exiting context')
async def run_async_with():
async with AsyncContextManager() as c:
print("使用 async with 来管理异步上下文")
print(c)
loop = asyncio.get_event_loop()
loop.run_until_complete(run_async_with())
loop.close()
输出
entering context
使用 async with 来管理异步上下文
返回值做为c的值
exiting context
网友评论