Python 的 异步上下文管理器

等级 5350 次按键

这使用__aenter__和__aexit__创建异步上下文管理器。与'async with'一起用于异步资源管理。

Python 代码

# 导入asyncio以支持async/await
# 提供事件循环和异步工具
1import asyncio
2
# class AsyncResource是异步上下文管理器
# 管理需要异步设置/清理的资源
3class AsyncResource:
# __aenter__是__enter__的异步版本
# 进入'async with'块时调用
4 async def __aenter__(self):
# 打印获取消息
5 print("Acquiring resource")
# 模拟如网络/文件的异步操作
6 await asyncio.sleep(0.1)
# 为'as'变量返回self
7 return self
8
# __aexit__是__exit__的异步版本
# *args捕获异常信息(如果有)
9 async def __aexit__(self, *args):
# 打印释放消息
10 print("Releasing resource")
# 模拟异步清理
11 await asyncio.sleep(0.1)
12
# use是普通的异步方法
# 在资源获取时调用
13 async def use(self):
14 print("Using resource")
15
# main是异步函数(协程)
# 异步代码的入口点
16async def main():
# 'async with'调用__aenter__和__aexit__
# r是__aenter__的返回值
17 async with AsyncResource() as r:
# 在持有资源时调用use()
18 await r.use()
19
# asyncio.run()创建事件循环并运行main
# 运行异步代码的标准方式
20asyncio.run(main())

运行结果

Acquiring resource
Using resource
Releasing resource
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • (× 13
  • )× 13
  • _× 8
  • :× 6
  • .× 6
  • "× 6
  • ,× 1
  • *× 1

Python 等级 5 的更多代码示例

← 返回 Python 打字练习