事业单位 网络网站建设,做网站用eclipse吗,html在线编辑网站,wordpress2019文章目录with语句自定义对象支持withcontextlib模块closing自动关闭suppress回避错误ExitStack清理Python 中的 with 语句用于清理工作#xff0c;封装了
try…except…finally编码范式#xff0c;提高了易用性。with语句
with语句有助于简化资源管理#xff1a;
# 离开作…
文章目录with语句自定义对象支持withcontextlib模块closing自动关闭suppress回避错误ExitStack清理Python 中的 with 语句用于清理工作封装了
try…except…finally编码范式提高了易用性。with语句
with语句有助于简化资源管理
# 离开作用域时自动关闭文件
with open(hello.txt, w) as f:f.write(hello, world!)自定义对象支持with
类只要实现上下文管理器就可获得with支持
类中实现__enter__和__exit__方法进入with语句上下文时__enter__被调用以获取资源离开with上下文时__exit__被调用以释放资源
class ManagedFile:def __init__(self, name):self.name namedef __enter__(self):self.file open(self.name, w)return self.filedef __exit__(self, exc_type, exc_val, exc_tb):if self.file:self.file.close()contextlib模块
使用contextlib.contextmanager装饰器能够使函数生成器自动支持with语句
函数要为生成器即有yield语句将yield语句前代码当做__enter__执行将yield语句之后代码当做__exit__执行yield返回值赋值给as后的变量
from contextlib import contextmanagercontextmanager
def managed_file(name):try:print(open file:, name)f open(name, w)yield ffinally:print(close file)f.close()with managed_file(rD:\temp\hello.txt) as f:print(write file)f.write(hello world!) closing自动关闭
closing装饰器封装有close的类在离开with作用域时自动调用close方法
from contextlib import closing
from urllib.request import urlopenwith closing(urlopen(http://www.baidu.com)) as page:# get the pagesuppress回避错误
suppress(*exceptions)可以禁止任意数目的异常
# 文件不存在也不会抛出异常
with suppress(FileNotFoundError):os.remove(somefile.tmp)ExitStack清理
ExitStack可组合多个清理器通过向栈中添加清理回调enter_context在离开with时统一清理
# 在离开时会统一关闭打开的文件即使部分文件在打开时抛出异常
with ExitStack() as stack:files [stack.enter_context(open(fname)) for fname in filenames]