<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>上下文管理器 on 老张开工了</title>
    <link>/%E4%B8%8A%E4%B8%8B%E6%96%87%E7%AE%A1%E7%90%86%E5%99%A8/</link>
    <description>Recent content in 上下文管理器 on 老张开工了</description>
    <generator>Hugo</generator>
    <language>zh-cn</language>
    <lastBuildDate>Tue, 19 May 2026 00:00:00 +0000</lastBuildDate>
    <atom:link href="/%E4%B8%8A%E4%B8%8B%E6%96%87%E7%AE%A1%E7%90%86%E5%99%A8/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>上下文管理器与 with 语句</title>
      <link>/posts/2026/05/context-managers/</link>
      <pubDate>Tue, 19 May 2026 00:00:00 +0000</pubDate>
      <guid>/posts/2026/05/context-managers/</guid>
      <description>上下文管理器（Context Manager）是 Python 中用于资源管理的核心机制。无论你是在读写文件、获取锁、打开数据库连接还是管理网络会话——with 语句都能确保资源被正确释放，即使发生异常也不例外。&#xA;为什么需要上下文管理器 传统方式的痛点 来看一个常见的文件操作：&#xA;# 传统方式：容易忘记关闭文件 f = open(&amp;#34;data.txt&amp;#34;, &amp;#34;r&amp;#34;) content = f.read() f.close() # 如果前面的代码抛异常，这一行不会执行！ # 改进：用 try/finally 确保关闭 f = open(&amp;#34;data.txt&amp;#34;, &amp;#34;r&amp;#34;) try: content = f.read() finally: f.close() # 无论是否异常，都会执行 虽然 try/finally 能解决问题，但代码显得冗长。如果每次资源操作都要写 try/finally，不仅繁琐而且容易遗漏。&#xA;使用 with 语句 # with 语句 —— 简洁且安全 with open(&amp;#34;data.txt&amp;#34;, &amp;#34;r&amp;#34;) as f: content = f.read() # 离开 with 块后，文件自动关闭 # 等价于 try/finally，但更简洁 with 语句的工作原理 with 语句的本质是执行上下文管理器的协议：&#xA;with EXPRESSION as VARIABLE: BLOCK 等价于：</description>
    </item>
  </channel>
</rss>
