首页 > 代码库 > with补充知识点
with补充知识点
import threading,queue,time import contextlib @contextlib.contextmanager def fun(list_1,val): list_1.append(val) try: yield finally: list_1.remove(val) q = queue.Queue() q.put(‘alxe‘) li = [] with fun(li,1): q.get()
class A: def __enter__(self): print (‘__enter__() called‘) def __exit__(self, e_t, e_v, t_b): print (‘__exit__() called‘) with A() as a: print(‘got instance‘)
from __future__ import with_statement from contextlib import contextmanager @contextmanager def context(): print (‘entering the zone‘) try: yield except Exception as e: print (‘with an error %s‘%e) raise e else: print (‘with no error‘) with context(): print (‘----in context call------‘)
文件打开关闭 import contextlib @contextlib.contextmanager def myopen(file_path,mode): f = open(file_path,mode,encoding=‘utf-8‘) try: yield f finally: f.close() with myopen(‘D:\E\semantic/sd.txt‘,‘r‘) as file_obj: print(file_obj.read())
with补充知识点
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。