1、from contextlib import contextmanager的作用

用装饰器的方式实现上下文管理,这里以为打文件为例

2、用法来源

在学习Kombu队列源码里面:kombu.mixins.ConsumerMixin.py

3、简单的示例

from contextlib import contextmanager

@contextmanager
def open_file():
    try:
        yield open('tasks.py', 'r', encoding='utf-8')
    finally:
        print('读取完成')

if __name__ == '__main__':
    with open_file() as rf:
        print(rf.readline())

4、kombu.mixins.ConsumerMixin.py源码部分

Python from contextlib import contextmanager的使用

 

相关文章:

  • 2022-12-23
  • 2021-09-21
  • 2022-12-23
  • 2021-06-30
  • 2021-07-23
  • 2022-01-17
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-03-08
  • 2022-12-23
  • 2021-06-13
相关资源
相似解决方案