脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python上下文管理的使用场景实例讲解

python上下文管理的使用场景实例讲解

2021-09-13 00:13小妮浅浅 Python

在本篇文章里小编给大家整理的是一篇关于python上下文管理的使用场景实例讲解内容,有兴趣的朋友们可以学习下。

1、上下文管理的使用场景

凡是要在代码块前后插入代码的场景,这点和装饰器类似。

资源管理类:申请和回收,包括打开文件、网络连接、数据库连接等;

权限验证。

2、实例

?
1
2
3
4
5
6
7
8
9
10
11
>>> 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 语法块内有异常发生时,会抛出异常给调用者。

?
1
2
3
4
5
6
7
8
9
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__方法中处理异常实例扩展:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

到此这篇关于python上下文管理的使用场景实例讲解的文章就介绍到这了,更多相关python上下文管理的使用场景内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.py.cn/jishu/jichu/27201.html

延伸 · 阅读

精彩推荐