python的上下文管理器 with
with 语句就是为了简化try 和 finally 这种写法
先看一个try 和 finally的例子
def try_ex(): try: print("code start") raise KeyError return 1 except KeyError as e: print("key error") return 2 else: print("other error") return 3 finally: print("finally") return 4
#上下文管理器协议 __enter__ __exit__ 两个魔法函数
class Sample: def __enter__(self): #获取资源 print("enter") return self def __exit__(self, exc_type, exc_val, exc_tb): #释放资源 print("exit") def do_thing(self): print("doing") with Sample() as sample: sample.do_thing()
#contextlib简化上下文管理器,利用了生成器的特性
import contextlib @contextlib.contextmanager #可以将定义的函数变为一个上下文管理器 def file_open(fiel_name): print("file open") #相当于__enter__ yield {} #将一个函数有生成器特性 print("file end") #相当于__exit__ with file_open("bobby,txt") as f_opened: print("file proccessing")
#with的使用
class TianMao(threading.Thread): def __init__(self, cond): super().__init__(name="天猫精灵") self.cond = cond def run(self): with self.cond: print("{} : 小爱同学 ".format(self.name)) self.cond.notify() self.cond.wait() class XiaoAi(threading.Thread): def __init__(self, cond): super().__init__(name="小爱") self.cond = cond def run(self): with self.cond: self.cond.wait() print("{} : 在 ".format(self.name)) self.cond.notify() if __name__ == "__main__": from concurrent import futures cond = threading.Condition() xiaoai = XiaoAi(cond) tianmao = TianMao(cond)