栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python“ with”语句的用途是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python“ with”语句的用途是什么?

我相信这已经在我之前的其他用户那里得到了回答,因此我仅出于完整性的考虑而添加:该with语句通过将通用的准备工作和清理任务封装在所谓的上下文管理器中来简化异常处理。可以在PEP 343中找到更多详细信息。例如,该open语句本身就是一个上下文管理器,它使你可以打开文件,只要with在使用它的语句上下文中执行该文件,就可以保持打开状态,并在离开上下文后立即将其关闭,无论你是因为异常还是在常规控制流程中离开了它。

with
因此,可以使用类似于C ++中的RAII模式的方式使用该语句:with语句并在你离开with上下文时释放。

一些示例是:使用打开文件,使用

with open(filename) as fp:
获取锁with lock:(在lock的实例
threading.Lock)
。你还可以使用中的
contextmanager
装饰器来构造自己的上下文管理器
contextlib
。例如,当我不得不临时更改当前目录然后返回到原来的位置时,我经常使用它:

from contextlib import contextmanagerimport os@contextmanagerdef working_directory(path):    current_dir = os.getcwd()    os.chdir(path)    try:        yield    finally:        os.chdir(current_dir)with working_directory("data/stuff"):    # do something within data/stuff# here I am back again in the original working directory

这是另一个示例,该示例临时重定向

sys.stdin,sys.stdout
并重定向
sys.stderr
到其他文件句柄并稍后将其还原:

from contextlib import contextmanagerimport sys@contextmanagerdef redirected(**kwds):    stream_names = ["stdin", "stdout", "stderr"]    old_streams = {}    try:        for sname in stream_names: stream = kwds.get(sname, None) if stream is not None and stream != getattr(sys, sname):     old_streams[sname] = getattr(sys, sname)     setattr(sys, sname, stream)        yield    finally:        for sname, stream in old_streams.iteritems(): setattr(sys, sname, stream)with redirected(stdout=open("/tmp/log.txt", "w")):     # these print statements will go to /tmp/log.txt     print "Test entry 1"     print "Test entry 2"# back to the normal stdoutprint "Back to normal stdout again"

最后,另一个示例创建一个临时文件夹并在离开上下文时清理它:

from tempfile import mkdtempfrom shutil import rmtree@contextmanagerdef temporary_dir(*args, **kwds):    name = mkdtemp(*args, **kwds)    try:        yield name    finally:        shutil.rmtree(name)with temporary_dir() as dirname:    # do whatever you want


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/374800.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号