一、上下文的基本实现
1、如下例,执行过程如下面代码:
#!usr/bin/env python # -*- coding:utf-8 -*- import queue import contextlib li = [] @contextlib.contextmanager #装饰器,上下文管理 def worker_state(lis,value): lis.append(value) try: yield 1111 finally: lis.remove(value) with worker_state(li,1) as f: """ 1、调用的是worker_state函数,并把参数传给函数 2、worker_state从下向上执行,当遇到yield是停止执行,并将yield的后面的对象赋值给f 3、worker_state函数遇到yield停止运行后,开始执行with后面的语句 4、执行完with语句后,执行worker_state函数中finally后的语句 """ print(li) print(f) print('执行......') print(li)
2、自己编写打开文件的with open的方法
#!usr/bin/env python # -*- coding:utf-8 -*- import contextlib @contextlib.contextmanager def myopen(file_path, open_mode): f = open(file_path, open_mode, encoding='utf-8') try: yield f finally: f.close() with myopen('qw','r') as f: re = f.read() print(re)