当前位置 博文首页 > python上下文管理的使用场景实例讲解

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

    作者:小妮浅浅 时间:2021-07-19 18:41

    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
    jsjbwy