python-with

使用方法:

每个自带 __enter____close__的对象均可使用with 语句进行异常处理

1
2
with context_expression [as target(s)]:
with-body

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
with open('xxx', 'r') as fIn:
lstLine = fIn.readlines()
# 会自动调用 fIn.close()函数 进行清理 相当于写 try...except...finally...

# 多项操作
with open("x.txt") as f1, open('xxx.txt') as f2:
do something with f1,f2


# 常规操作
try:
with open('xxx', 'r') as fIn:
stLine = fIn.readlines()
...

except Exception as e:
print(e)

工作原理:

当使用with语句时, with 会自动调用目标对象的
self.__enter__()函数, 让对象自行初始化资源等操作

然后当出作用域时,会自动调用self.__close__()函数
让对象自行处理资源释放操作

with 工作流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
context_manager = context_expression
exit = type(context_manager).__exit__
value = type(context_manager).__enter__(context_manager)
exc = True # True 表示正常执行,即便有异常也忽略;False 表示重新抛出异常,需要对异常进行处理
try:
try:
target = value # 如果使用了 as 子句
with-body # 执行 with-body
except:
# 执行过程中有异常发生
exc = False
# 如果 __exit__ 返回 True,则异常被忽略;如果返回 False,则重新抛出异常
# 由外层代码对异常进行处理
if not exit(context_manager, *sys.exc_info()):
raise
finally:
# 正常退出,或者通过 statement-body 中的 break/continue/return 语句退出
# 或者忽略异常退出
if exc:
exit(context_manager, None, None, None)
# 缺省返回 None,None 在布尔上下文中看做是 False

参考:

浅谈 Python 的 with 语句
理解Python中的with…as…语法

文章目录
  1. 1. 使用方法:
    1. 1.1. 例子:
  2. 2. 工作原理:
    1. 2.1. with 工作流程
  3. 3. 参考:
|