Python with语句详解:上下文管理器与资源释放

雨后青山
雨后青山
发布时间:2026-10-14| 7人浏览过
原创

本文深入解析Python中with语句的工作原理及其在资源管理中的应用。通过介绍上下文管理器概念,展示如何利用内置对象、自定义类及contextlib模块实现文件关闭、锁获取等资源的自动清理。文章包含具体代码示例,演示四种典型使用场景,帮助开发者编写更安全、简洁的资源处理代码。

with语句简介与背景

with语句自Python 2.5版本引入,旨在处理与异常相关的资源访问场景。在2.5版本中,需通过`from __future__ import with_statement`导入方可使用;从2.6版本起该功能默认启用(详见What's new in Python 2.6中关于with语句的介绍)。该语句适用于需要确保资源访问安全的场合,无论操作过程中是否发生异常,都能执行必要的“清理”动作以释放资源,例如文件使用后的自动关闭、线程中锁的自动获取与释放等。

核心概念:上下文管理器

术语

使用with语句的前提是理解上下文管理器(Context Manager)的概念。只有实现了上下文管理器协议的对象,才能与with语句配合工作。

资源释放的两种实现方式

在Python中进行资源读写操作后,必须正确释放资源。虽然可以使用try…finally结构来确保资源释放,但Python提供的with语句提供了更简洁的实现方式。

with语句的四种使用场景

1. Python内置的如文件操作open()等函数已可直接支持with语句。

2. 可以自定义支持with语句的对象。

3. 利用contextlib模块也可以创建支持with语句的对象。

4. 针对需要执行close操作的对象,with语句的使用方式。

示例代码中展示了4种不同的使用标注场景。

代码示例:自定义与内置支持


# 自定义支持with语句的对象
class DummyRes:
  def __init__(self, tag):
    self.tag = tag
  def __enter__(self):
    print("Enter >>> {}".format(self.tag))
    return self
  def __exit__(self, exc_type, exc_value, exc_tb):
    print("Exit <<< {}".format(self.tag))
    if exc_tb is None:
      print("Exit without Exception {}".format(self.tag))
      return False
    else:
      print("Exit with Exception {}".format(self.tag))
      return True
# 支持closing 上下文with语句对象
class Closing:
  def __init__(self, thing):
    self.thing = thing
  def __enter__(self):
    return self
  def __exit__(self, exc_type, exc_value, exc_tb):
    self.thing.close()
class ClosingDemo:
  def __init__(self):
    self.acquire()
  def acquire(self):
    print("Acquire RES")
  def close(self):
    print("Close RES")
from contextlib import contextmanager
class ContextDemo:
  def __init__(self):
    print("Context Demo init")
    raise Exception
    print("Context Demo init")
  def print(self):
    print("Context Demo print 1")
    #raise Exception
    print("Context Demo print 2")
  def close(self):
    print("Context Demo close")
def context_demo():
  print("context demo in")
  raise Exception
  print("context demo out")
@contextmanager
def demo():
  print("Allocate Resoures")
  try:
    yield context_demo
  finally:
    print("raise exception")
  #yield "*** contextmanager demo ***"
  print("Free Resoures")
if __name__ == "__main__":
  # 1. 使用with语句 (自动关闭文件)
  with open("test.txt", "w") as f:
    f.write("write test")
  # 2. 自动定义with语句
  with DummyRes("test") as res:
    print("With body 1")
    raise Exception
    print("With body 2")
  # 3. 利用contextlib定义with语句
  with demo():
    print("exc demo")
  # 4. closing 上下文 (适合有close操作的情况)
  with Closing(ClosingDemo()):
    print("Use Resoures")

总结与展望

总结

以上介绍了Python with语句的基本用法,希望能帮助读者理解其原理与应用。如有任何疑问,欢迎留言讨论,小编会及时回复。感谢大家对本站的支持!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。