一文带你搞懂Python上下文管理器
作者:曲鸟 时间:2022-11-26 05:15:50
一、什么是上下文管理器
我们在处理文件的时候经常看到下面这样的代码,它即是上下文管理器:
with open('test.txt', encoding='utf-8') as f:
print(f.readlines())
它的含义是打开当前目录下的test.txt文件并打印它里面的内容,与下面的代码效果是一样的:
f = open('test.txt', encoding='utf-8')
print(f.readlines())
f.close()
对比两种写法能够发现,使用with自动执行了f.close()(关闭文件)的这步操作,能够少写一点代码。
那这样的上下文管理器是怎么实现的,下面为你讲解。
二、如何实现上下文管理器
1. 通过类实现
如果要实现上面open
的上下文管理器功能,我们可以通过创建一个类,并添加__enter__
和__exit__
方法即可,如下面的代码所示:
class DiyOpen(object):
def __init__(self, filename, **kwargs):
self.f = open(filename, **kwargs)
def __enter__(self):
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
print('关闭文件')
self.f.close()
with DiyOpen('test.txt', encoding='utf-8') as f:
print(f.readlines())
输出结果
['第一行\n', '第二行\n', '第三行']
关闭文件
可以看到在我们打印出文件内容后,自动执行了关闭文件的操作。
那__enter__
和__exit__
的含义是什么,__exit__
后面的exc_type
, exc_val
, exc_tb
又是什么意思呢?
1)_enter_
__enter__
相对来说好理解的多,当出现with语句时,它就会被触发,有返回值时,会把返回值赋值给as声明的变量,也就是我们上面的as f中的f。
2)_exit_
__exit__
是在with执行完成后自动执行的,他后面的参数含义如下:
exc_type
:异常类型exc_val
:异常原因exc_tb
:堆栈追踪信息
当with中执行的代码报错时,除了不继续执行with包含的代码外,还会将报错信息放入上面的三个参数中,例如下面的代码:
class DiyOpen(object):
def __init__(self, filename, **kwargs):
self.f = open(filename, **kwargs)
def __enter__(self):
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
print(exc_type)
print(exc_val)
print(exc_tb)
self.f.close()
with DiyOpen('test.txt', encoding='utf-8') as f:
print(f.no())
输出结果
<class 'AttributeError'>
'_io.TextIOWrapper' object has no attribute 'no'
<traceback object at 0x000002A34B834900>
需要注意的是:
我们可以手动指定__exit__的返回值为True让它不报错。
没有异常信息时,上面的三个参数值都会为None
2. 通过contextlib实现
Python内置了contextlib
这个模块用于实现上下文管理器,它是通过生成器yield实现的,这个模块让我们不必再创建类和__enter__和__exit__了。
通过contextlib
实现open功能的代码如下:
from contextlib import contextmanager
@contextmanager
def diy_open(filename, **kwargs):
f = open(filename, **kwargs) # __init__
try:
yield f # __enter__
finally: # __exit__
f.close()
with diy_open('test.txt', encoding='utf-8') as f:
print(f.readlines())
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!
来源:https://blog.csdn.net/momoda118/article/details/121988918
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python创建文件备份的脚本
解决python中os.system调用exe文件的问题
![](https://img.aspxhome.com/file/2023/0/63190_0s.png)
js树插件zTree获取所有选中节点数据的方法
Mysql存储过程中游标的用法实例
在Python中通过机器学习实现人体姿势估计
![](https://img.aspxhome.com/file/2023/0/127650_0s.png)
FrontPage2002简明教程六:图片库
源码分析系列之json_encode()如何转化一个对象
使用xtrabackup实现mysql备份
使用python实现时间序列白噪声检验方式
![](https://img.aspxhome.com/file/2023/9/118079_0s.jpg)
python装饰器原理源码示例分析
![](https://img.aspxhome.com/file/2023/6/133856_0s.png)
Django 如何从request中获取前端数据
pycharm 如何查看某一函数源码的快捷键
![](https://img.aspxhome.com/file/2023/4/69604_0s.png)
asp,php,.net使用301重定向方法
Vue如何引入远程JS文件
Python爬虫之爬取二手房信息
![](https://img.aspxhome.com/file/2023/9/68869_0s.jpg)
Python实现mysql数据库更新表数据接口的功能
在ASP中按指定参数格式化显示时间的函数。
html+vue.js 实现漂亮分页功能可兼容IE
![](https://img.aspxhome.com/file/2023/1/126531_0s.gif)
ASP中Global.asa使用方法说明
MySQL中由load data语句引起死锁的解决案例
![](https://img.aspxhome.com/file/2023/6/121586_0s.png)