jwenjian / ghiblog

GitHub Issues Blog, powered by GitHub Issues and GitHub Actions

Home Page:https://1link.fun

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

转载-浅谈 Python 的 with 语句

jwenjian opened this issue · comments

with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能(2.5 版本中要通过 from future import with_statement 导入后才可以使用),从 2.6 版本开始缺省可用(参考 What's new in Python 2.6? 中 with 语句相关部分介绍)。with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。

摘自: 浅谈 Python 的 with 语句