上下文管理器:
With open就是上下文管理器的例子。
几个概念:
1. 上下文表达式:with open(‘test.txt’) as f:
2. 上下文管理器:open(‘test.txt’)
3. f 不是上下文管理器,应该是资源对象。
具体详情:
异步上下文管理器:
此种对象通过定义 __aenter__() 和 __aexit__() 方法来对 async with 语句中的环境进行控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import asyncio class AsyncContextManager(object): def __init__(self): self.conn = None async def do_something(self): # 执行一个异步操作 return "do something" async def __aenter__(self): self.conn = await asyncio.sleep(1) return self async def __aexit__(self, exc_type, exc, tb): await asyncio.sleep(1) async def func(): async with AsyncContextManager() as f: result = await f.do_something() print(result) asyncio.run(func()) |

这个异步上下文管理器可以用于处理开发过程中的打开、处理、关闭这些循环操作