python上下文管理的使用场景实例讲解
作者:小妮浅浅 时间:2022-01-31 08:38:33
1、上下文管理的使用场景
凡是要在代码块前后插入代码的场景,这点和装饰器类似。
资源管理类:申请和回收,包括打开文件、网络连接、数据库连接等;
权限验证。
2、实例
>>> with Context():
... raise Exception # 直接抛出异常
...
enter context
exit context
Traceback (most recent call last):
File "/usr/local/python3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-4-63ba5aff5acc>", line 2, in <module>
raise Exception
Exception
知识点扩展:
python上下文管理器异常问题解决方法
异常实例
如果我们需要对异常做特殊处理,就可以在这个方法中实现自定义逻辑。
之所以 with 能够自动关闭文件资源,就是因为内置的文件对象实现了上下文管理器协议,这个文件对象的 __enter__ 方法返回了文件句柄,并且在 __exit__ 中实现了文件资源的关闭,另外,当 with 语法块内有异常发生时,会抛出异常给调用者。
class File:
def __enter__(self):
return file_obj
def __exit__(self, exc_type, exc_value, exc_tb):
# with 退出时释放文件资源
file_obj.close()
# 如果 with 内有异常发生 抛出异常
if exc_type is not None:
raise exception
在__exit__方法中处理异常实例扩展:
class File(object):
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, type, value, traceback):
print("Exception has been handled")
self.file_obj.close()
return True
with File('demo.txt', 'w') as opened_file:
opened_file.undefined_function()
# Output: Exception has been handled
来源:https://www.py.cn/jishu/jichu/27201.html
标签:python,上下文管理
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
RDFa介绍——构建更友好的web页面
2009-09-19 17:01:00
Python调用Windows命令打印文件
2022-01-17 14:07:25
Javascript实现的鼠标经过时播放声音
2010-05-18 20:03:00
如何动态产生变量?
2009-11-18 16:33:00
CSS Type set: 在线字体调整工具
2008-03-02 15:36:00
![](https://img.aspxhome.com/file/UploadPic/20083/2/csstypeset-snap_96s.gif)
python实现发送QQ邮件(可加附件)
2023-01-21 18:37:00
![](https://img.aspxhome.com/file/2023/8/93778_0s.png)
PHP实现的curl批量请求操作示例
2023-11-17 01:51:10
Django中对通过测试的用户进行限制访问的方法
2021-08-27 16:42:46
asp.net 防止用户通过后退按钮重复提交表单
2023-07-21 00:03:54
python asyncio 协程库的使用
2022-09-13 13:28:16
OpenCV中resize函数插值算法的实现过程(五种)
2021-07-09 21:05:24
![](https://img.aspxhome.com/file/2023/5/93815_0s.png)
关于select元素的两个小问题
2008-12-25 13:41:00
使用keras时input_shape的维度表示问题说明
2023-05-10 02:52:25
![](https://img.aspxhome.com/file/2023/3/92193_0s.jpg)
python读取图片的方式,以及将图片以三维数组的形式输出方法
2023-08-05 04:09:26
![](https://img.aspxhome.com/file/2023/5/89065_0s.jpg)
Python中pywifi模块的基本用法讲解
2023-09-23 00:21:00
解析go语言调用约定多返回值实现原理
2023-10-08 23:38:06
MySQL安全大讲堂:MySQL数据库安全配置
2009-10-18 11:24:00
python退出循环的方法
2022-06-10 07:24:35
Python 对输入的数字进行排序的方法
2022-11-10 13:11:36
Django缓存系统实现过程解析
2021-07-22 23:18:09