199 lines
434 KiB
HTML
199 lines
434 KiB
HTML
|
<!DOCTYPE html>
|
|||
|
<html><head><title>资源管理</title><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta property="og:title" content="资源管理"/><meta property="og:description" content="Python 的资源管理,以及自定义资源管理器和高级应用."/><meta property="og:image" content="https://wiki.7wate.com/static/og-image.png"/><meta property="og:width" content="1200"/><meta property="og:height" content="675"/><link rel="icon" href="../../../../static/icon.png"/><meta name="description" content="Python 的资源管理,以及自定义资源管理器和高级应用."/><meta name="generator" content="Quartz"/><link rel="preconnect" href="https://fonts.googleapis.com"/><link rel="preconnect" href="https://fonts.gstatic.com"/><script async src="https://umami.7wate.com/script.js" data-website-id="c061efdc-95dd-4d21-9d04-a1ffda0a85b9"></script><script>
|
|||
|
var _hmt = _hmt || [];
|
|||
|
(function() {
|
|||
|
var hm = document.createElement("script");
|
|||
|
hm.src = "https://hm.baidu.com/hm.js?94d8ccb156eb7c65abf317e6e01cdba9";
|
|||
|
var s = document.getElementsByTagName("script")[0];
|
|||
|
s.parentNode.insertBefore(hm, s);
|
|||
|
})();
|
|||
|
</script><script async src="https://www.googletagmanager.com/gtag/js?id=G-MHMEL0F832"></script><script>
|
|||
|
(function() {
|
|||
|
window.dataLayer = window.dataLayer || [];
|
|||
|
function gtag() {
|
|||
|
window.dataLayer.push(arguments);
|
|||
|
}
|
|||
|
gtag('js', new Date());
|
|||
|
gtag('config', 'G-MHMEL0F832');
|
|||
|
})();
|
|||
|
</script><link href="../../../../index.css" rel="stylesheet" type="text/css" spa-preserve/><link href="https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/katex.min.css" rel="stylesheet" type="text/css" spa-preserve/><link href="https://fonts.googleapis.com/css2?family=IBM Plex Mono&family=Schibsted Grotesk:wght@400;700&family=Source Sans Pro:ital,wght@0,400;0,600;1,400;1,600&display=swap" rel="stylesheet" type="text/css" spa-preserve/><script src="../../../../prescript.js" type="application/javascript" spa-preserve></script><script type="application/javascript" spa-preserve>const fetchData = fetch(`../../../../static/contentIndex.json`).then(data => data.json())</script></head><body data-slug="Tech/programming-language/Python/进阶/资源管理"><div id="quartz-root" class="page"><div id="quartz-body"><div class="left sidebar"><h1 class="page-title "><a href="../../../..">📚 X·Eden</a></h1><div class="spacer mobile-only"></div><div class="search "><div id="search-icon"><p>Search</p><div></div><svg tabIndex="0" aria-labelledby="title desc" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19.9 19.7"><title id="title">Search</title><desc id="desc">Search</desc><g class="search-path" fill="none"><path stroke-linecap="square" d="M18.5 18.3l-5.4-5.4"></path><circle cx="8" cy="8" r="7"></circle></g></svg></div><div id="search-container"><div id="search-space"><input autocomplete="off" id="search-bar" name="search" type="text" aria-label="Search for something" placeholder="Search for something"/><div id="results-container"></div></div></div></div><div class="darkmode "><input class="toggle" id="darkmode-toggle" type="checkbox" tabIndex="-1"/><label id="toggle-label-light" for="darkmode-toggle" tabIndex="-1"><svg xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" version="1.1" id="dayIcon" x="0px" y="0px" viewBox="0 0 35 35" style="enable-background:new 0 0 35 35;" xmlSpace="preserve"><title>Light mode</title><path d="M6,17.5C6,16.672,5.328,16,4.5,16h-3C0.672,16,0,16.672,0,17.5 S0.672,19,1.5,19h3C5.328,19,6,18.328,6,17.5z M7.5,26c-0.414,0-0.789,0.168-1.061,0.439l-2,2C4.168,28.711,4,29.086,4,29.5 C4,30.328,4.671,31,5.5,31c0.414,0,0.789-0.168,1.06-0.44l2-2C8.832,28.289,9,27.914,9,27.5C9,26.672,8.329,26,7.5,26z M17.5,6 C18.329,6,19,5.328,19,4.5v-3C19,0.672,18.329,0,17.5,0S16,0.672,16,1.5v3C16,5.328,16.671,6,17.5,6z M27.5,9 c0.414,0,0.789-0.168,1.06-0.439l2-2C30.832,6.289,31,5.914,31,5.5C31,4.672,30.329,4,29.5,4c-0.414,0-0.789,0.168-1.061,0.44 l-2,2C26.168,6.711,26,7.086,26,7.5C26,8.328,26.671,9,27.5,9z M6.439,8.561C6.711,8.832,7.086,9,7.5,9C8.328,9,9,8.328,9,7.5 c0-0.414-0.168-0.789-0.439-1.061l-2-2C6.289,4.168,5.914,4,5.5,4C4.672,4,4,4.672,4,5.5c0,0.414,0.168,0.789,0.439,1.06 L6.439,8.561z M33.5,16h-3c-0.828,0-1.5,0.672-1.5,1.5s0.672,1.5,1.5,1.5h3c0.828,0,1.5-0.672,1.5-1.5S34.328,16,33.5,16z M28.561,26.439C28.289,26.168,27.914,26,27.5,26c-0.828,0-1.5,0.672-1.5,1.5c0,0.414,0.168,0.789,0.439,1.06l2,2 C28.711,30.832,29.086,31,29.5,31c0.828,0,1.5-0.672,1.5-1.5c0-0.414-0.168-0.789-0.439-1.061L28.561,26.439z M17.5,29 c-0.829,0-1.5,0.672-1.5,1.5v3c0,0.828,0.671,1.5,1.5,1.5s1.5-0.672,1.5-1.5v-3C19,29.672,18.329,29,17.5,29z M17.5,7 C11.71,7,7,11.71,7,17.5S11.71,28,17.5,28S28,23.29,28,17.5S23.29,7,17.5,7z M17.5,25c-4.136,0-7.5-3.364-7.5-7.5 c0-4.136,3.364-7.5,7.5-7.5c4.136,0,7.5,3.364,7.5,7.5C25,21.636,21.636,25,17.5,25z"></path></svg></label><label id="toggle-label-dark" for="darkmode-toggle" tabIndex="-1"><svg xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" version="1.1" id="nightIcon" x="0px" y="0px" viewBox="0 0 100 100" style="enable-background='new 0 0 100 100'" xmlSpace="preserve"><title>Dark mode</title><path d="M96.76,66.458c-0.853-0.852-2.15-1.064-3.23-0.534c-6.063,2.991-12.858,4.571-19.655,4.571 C62.022,70.495,50.88,65.88,42.5,57.5C29.043,44.043,25.658,23.536,34.076,6.47c0.532-1.08,0.318-2.379-0.534-3.23 c-0.851-0.852-2.15-1.064-3.23-0.534c-4.918,2.427-9.375,5.619-13.246,9.491c-9.447,9.447-14.65,22.008-14.65
|
|||
|
<h2 id="with-语句和上下文管理器的原理"><code>with</code> 语句和上下文管理器的原理<a aria-hidden="true" tabindex="-1" href="#with-语句和上下文管理器的原理" class="internal"> §</a></h2>
|
|||
|
<p>Python 中的 <code>with</code> 语句是围绕上下文管理器概念设计的。它主要用于场景,如文件操作,以确保文件即使在出现错误的情况下也会被正确关闭。</p>
|
|||
|
<p>上下文管理器是实现了特定协议的对象,该协议包含两个魔术方法:<code>__enter__()</code> 和 <code>__exit__()</code>。<code>__enter__()</code> 方法在进入 <code>with</code> 语句块前执行,而 <code>__exit__()</code> 方法则在退出 <code>with</code> 语句块时执行,即使是通过异常退出。</p>
|
|||
|
<div data-rehype-pretty-code-fragment><pre style="background-color:var(--shiki-color-background);" tabindex="0" data-language="python" data-theme="default"><code data-language="python" data-theme="default"><span data-line><span style="color:var(--shiki-token-keyword);">with</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">open</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">'example.txt'</span><span style="color:var(--shiki-token-punctuation);">, </span><span style="color:var(--shiki-token-string-expression);">'w'</span><span style="color:var(--shiki-token-punctuation);">)</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">as</span><span style="color:var(--shiki-color-text);"> file</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> file</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">write</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">'Hello, World!'</span><span style="color:var(--shiki-token-punctuation);">)</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-comment);"># 文件在这里已自动关闭</span></span></code></pre></div>
|
|||
|
<p>在此示例中,<code>open</code> 函数返回的文件对象是一个上下文管理器,它保证了文件在离开 <code>with</code> 块后会自动关闭。</p>
|
|||
|
<h2 id="自定义资源管理">自定义资源管理<a aria-hidden="true" tabindex="-1" href="#自定义资源管理" class="internal"> §</a></h2>
|
|||
|
<h3 id="自定义上下文管理器的实现">自定义上下文管理器的实现<a aria-hidden="true" tabindex="-1" href="#自定义上下文管理器的实现" class="internal"> §</a></h3>
|
|||
|
<p>创建自定义上下文管理器需要定义一个类并实现 <code>__enter__</code> 和 <code>__exit__</code> 方法。这样的类可以用来管理自定义资源,比如数据库连接。</p>
|
|||
|
<div data-rehype-pretty-code-fragment><pre style="background-color:var(--shiki-color-background);" tabindex="0" data-language="python" data-theme="default"><code data-language="python" data-theme="default"><span data-line><span style="color:var(--shiki-token-keyword);">class</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">MyDatabase</span><span style="color:var(--shiki-color-text);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">def</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">__enter__</span><span style="color:var(--shiki-color-text);">(</span><span style="color:var(--shiki-token-parameter);">self</span><span style="color:var(--shiki-color-text);">):</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-comment);"># 初始化数据库连接</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">return</span><span style="color:var(--shiki-color-text);"> self</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">def</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">__exit__</span><span style="color:var(--shiki-color-text);">(</span><span style="color:var(--shiki-token-parameter);">self</span><span style="color:var(--shiki-token-punctuation);">,</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-parameter);">exc_type</span><span style="color:var(--shiki-token-punctuation);">,</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-parameter);">exc_value</span><span style="color:var(--shiki-token-punctuation);">,</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-parameter);">traceback</span><span style="color:var(--shiki-color-text);">):</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-comment);"># 清理资源,如关闭连接</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">pass</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">with</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">MyDatabase</span><span style="color:var(--shiki-token-punctuation);">()</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">as</span><span style="color:var(--shiki-color-text);"> db</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-comment);"># 使用数据库连接</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">pass</span></span></code></pre></div>
|
|||
|
<h3 id="contextlib-模块的应用"><code>contextlib</code> 模块的应用<a aria-hidden="true" tabindex="-1" href="#contextlib-模块的应用" class="internal"> §</a></h3>
|
|||
|
<p><code>contextlib</code> 模块提供了更简洁的方法来创建上下文管理器,尤其是对于函数装饰器。使用 <code>contextlib.contextmanager</code> 装饰器,可以通过一个生成器定义上下文管理逻辑。</p>
|
|||
|
<div data-rehype-pretty-code-fragment><pre style="background-color:var(--shiki-color-background);" tabindex="0" data-language="python" data-theme="default"><code data-language="python" data-theme="default"><span data-line><span style="color:var(--shiki-token-keyword);">import</span><span style="color:var(--shiki-color-text);"> time</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">from</span><span style="color:var(--shiki-color-text);"> contextlib </span><span style="color:var(--shiki-token-keyword);">import</span><span style="color:var(--shiki-color-text);"> contextmanager</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-function);">@contextmanager</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">def</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">timer</span><span style="color:var(--shiki-color-text);">():</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> start </span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-color-text);"> time</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">time</span><span style="color:var(--shiki-token-punctuation);">()</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">yield</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> end </span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-color-text);"> time</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">time</span><span style="color:var(--shiki-token-punctuation);">()</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">print</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-keyword);">f</span><span style="color:var(--shiki-token-string-expression);">"运行时间: </span><span style="color:var(--shiki-token-constant);">{</span><span style="color:var(--shiki-token-punctuation);">end </span><span style="color:var(--shiki-token-keyword);">-</span><span style="color:var(--shiki-token-punctuation);"> start</span><span style="color:var(--shiki-token-constant);">}</span><span style="color:var(--shiki-token-string-expression);"> 秒"</span><span style="color:var(--shiki-token-punctuation);">)</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">with</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">timer</span><span style="color:var(--shiki-token-punctuation);">():</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">for</span><span style="color:var(--shiki-color-text);"> _ </span><span style="color:var(--shiki-token-keyword);">in</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">range</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-constant);">1000000</span><span style="color:var(--shiki-token-punctuation);">):</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">pass</span></span></code></pre></div>
|
|||
|
<h2 id="高级应用">高级应用<a aria-hidden="true" tabindex="-1" href="#高级应用" class="internal"> §</a></h2>
|
|||
|
<h3 id="在并发环境中的资源管理">在并发环境中的资源管理<a aria-hidden="true" tabindex="-1" href="#在并发环境中的资源管理" class="internal"> §</a></h3>
|
|||
|
<p>在 <a href="../../../../Tech/programming-language/Python/进阶/并行和并发" class="internal" data-slug="Tech/programming-language/Python/进阶/并行和并发">多线程和多进程</a> 环境中,资源管理变得更加重要。使用线程/进程安全的上下文管理器可以确保资源在并发环境下安全地使用和释放。</p>
|
|||
|
<div data-rehype-pretty-code-fragment><pre style="background-color:var(--shiki-color-background);" tabindex="0" data-language="python" data-theme="default"><code data-language="python" data-theme="default"><span data-line><span style="color:var(--shiki-token-keyword);">from</span><span style="color:var(--shiki-color-text);"> threading </span><span style="color:var(--shiki-token-keyword);">import</span><span style="color:var(--shiki-color-text);"> Thread</span><span style="color:var(--shiki-token-punctuation);">,</span><span style="color:var(--shiki-color-text);"> Lock</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-comment);"># 共享资源</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);">counter </span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-constant);">0</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-comment);"># 创建一个锁对象</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);">lock </span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">Lock</span><span style="color:var(--shiki-token-punctuation);">()</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">def</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">increment_counter</span><span style="color:var(--shiki-color-text);">():</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">global</span><span style="color:var(--shiki-color-text);"> counter</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">with</span><span style="color:var(--shiki-color-text);"> lock</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-comment);"># 在这个区块内,counter 变量被锁保护</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">for</span><span style="color:var(--shiki-color-text);"> _ </span><span style="color:var(--shiki-token-keyword);">in</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">range</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-constant);">100000</span><span style="color:var(--shiki-token-punctuation);">):</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> counter </span><span style="color:var(--shiki-token-keyword);">+=</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-constant);">1</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-comment);"># 创建线程列表</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);">threads </span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-color-text);"> []</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-comment);"># 创建并启动5个线程</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">for</span><span style="color:var(--shiki-color-text);"> _ </span><span style="color:var(--shiki-token-keyword);">in</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">range</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-constant);">5</span><span style="color:var(--shiki-token-punctuation);">):</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> thread </span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">Thread</span><span style="color:var(--shiki-token-punctuation);">(target</span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-token-punctuation);">increment_counter)</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> thread</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">start</span><span style="color:var(--shiki-token-punctuation);">()</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> threads</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">append</span><span style="color:var(--shiki-token-punctuation);">(thread)</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-comment);"># 等待所有线程完成</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">for</span><span style="color:var(--shiki-color-text);"> thread </span><span style="color:var(--shiki-token-keyword);">in</span><span style="color:var(--shiki-color-text);"> threads</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> thread</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">join</span><span style="color:var(--shiki-token-punctuation);">()</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-comment);"># 输出最终的计数器值</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-function);">print</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-keyword);">f</span><span style="color:var(--shiki-token-string-expression);">"最终计数器值: </span><span style="color:var(--shiki-token-constant);">{</span><span style="color:var(--shiki-token-punctuation);">counter</span><span style="color:var(--shiki-token-constant);">}</span><span style="color:var(--shiki-token-string-expression);">"</span><span style="color:var(--shiki-token-punctuation);">)</span></span></code></pre></div>
|
|||
|
<h3 id="管理网络">管理网络<a aria-hidden="true" tabindex="-1" href="#管理网络" class="internal"> §</a></h3>
|
|||
|
<p>确保网络和数据库连接在使用后正确关闭是非常重要的,以避免资源泄漏。</p>
|
|||
|
<div data-rehype-pretty-code-fragment><pre style="background-color:var(--shiki-color-background);" tabindex="0" data-language="python" data-theme="default"><code data-language="python" data-theme="default"><span data-line><span style="color:var(--shiki-token-keyword);">import</span><span style="color:var(--shiki-color-text);"> requests</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">with</span><span style="color:var(--shiki-color-text);"> requests</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">Session</span><span style="color:var(--shiki-token-punctuation);">()</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">as</span><span style="color:var(--shiki-color-text);"> session</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> response </span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-color-text);"> session</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">get</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">'https://example.com'</span><span style="color:var(--shiki-token-punctuation);">)</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">if</span><span style="color:var(--shiki-color-text);"> response</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-color-text);">status_code </span><span style="color:var(--shiki-token-keyword);">==</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-constant);">200</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">print</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">"成功获取网页内容!"</span><span style="color:var(--shiki-token-punctuation);">)</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">print</span><span style="color:var(--shiki-token-punctuation);">(response.text)</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">else</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">print</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">"请求失败,状态码:"</span><span style="color:var(--shiki-token-punctuation);">, response.status_code)</span></span>
|
|||
|
<span data-line> </span></code></pre></div>
|
|||
|
<h3 id="数据库连接">数据库连接<a aria-hidden="true" tabindex="-1" href="#数据库连接" class="internal"> §</a></h3>
|
|||
|
<p>假设我们使用的是 Python 的 <code>sqlite3</code> 库来管理 SQLite 数据库连接。这个示例将展示如何创建一个上下文管理器来处理数据库连接和事务。</p>
|
|||
|
<p>首先,导入所需的库并设置数据库连接:</p>
|
|||
|
<div data-rehype-pretty-code-fragment><pre style="background-color:var(--shiki-color-background);" tabindex="0" data-language="python" data-theme="default"><code data-language="python" data-theme="default"><span data-line><span style="color:var(--shiki-token-keyword);">import</span><span style="color:var(--shiki-color-text);"> sqlite3</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">from</span><span style="color:var(--shiki-color-text);"> contextlib </span><span style="color:var(--shiki-token-keyword);">import</span><span style="color:var(--shiki-color-text);"> contextmanager</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-comment);"># 定义数据库连接函数</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-function);">@contextmanager</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">def</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">get_db_connection</span><span style="color:var(--shiki-color-text);">(</span><span style="color:var(--shiki-token-parameter);">database</span><span style="color:var(--shiki-color-text);">):</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">try</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-comment);"># 创建数据库连接</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> conn </span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-color-text);"> sqlite3</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">connect</span><span style="color:var(--shiki-token-punctuation);">(database)</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">print</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">"数据库连接成功"</span><span style="color:var(--shiki-token-punctuation);">)</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">yield</span><span style="color:var(--shiki-color-text);"> conn</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">except</span><span style="color:var(--shiki-color-text);"> sqlite3</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-color-text);">Error </span><span style="color:var(--shiki-token-keyword);">as</span><span style="color:var(--shiki-color-text);"> e</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">print</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-keyword);">f</span><span style="color:var(--shiki-token-string-expression);">"数据库连接错误: </span><span style="color:var(--shiki-token-constant);">{</span><span style="color:var(--shiki-token-punctuation);">e</span><span style="color:var(--shiki-token-constant);">}</span><span style="color:var(--shiki-token-string-expression);">"</span><span style="color:var(--shiki-token-punctuation);">)</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">finally</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-comment);"># 关闭数据库连接</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> conn</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">close</span><span style="color:var(--shiki-token-punctuation);">()</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">print</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">"数据库连接关闭"</span><span style="color:var(--shiki-token-punctuation);">)</span></span>
|
|||
|
<span data-line> </span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-keyword);">if</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-constant);">__name__</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">==</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-string-expression);">"__main__"</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-comment);"># 使用上下文管理器执行数据库操作</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">with</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-function);">get_db_connection</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">'my_database.db'</span><span style="color:var(--shiki-token-punctuation);">)</span><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-keyword);">as</span><span style="color:var(--shiki-color-text);"> conn</span><span style="color:var(--shiki-token-punctuation);">:</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> cursor </span><span style="color:var(--shiki-token-keyword);">=</span><span style="color:var(--shiki-color-text);"> conn</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">cursor</span><span style="color:var(--shiki-token-punctuation);">()</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-comment);"># 执行一些数据库操作</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> cursor</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">execute</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">'''CREATE TABLE IF NOT EXISTS my_table </span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-token-string-expression);"> (id INTEGER PRIMARY KEY, name TEXT)'''</span><span style="color:var(--shiki-token-punctuation);">)</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> cursor</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">execute</span><span style="color:var(--shiki-token-punctuation);">(</span><span style="color:var(--shiki-token-string-expression);">'''INSERT INTO my_table (name) VALUES ('Alice')'''</span><span style="color:var(--shiki-token-punctuation);">)</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> </span><span style="color:var(--shiki-token-comment);"># 提交事务</span></span>
|
|||
|
<span data-line><span style="color:var(--shiki-color-text);"> conn</span><span style="color:var(--shiki-token-punctuation);">.</span><span style="color:var(--shiki-token-function);">commit</span><span style="color:var(--shiki-token-punctuation);">()</span></span></code></pre></div>
|
|||
|
<p>在这个示例中,我们首先创建了一个名为 <code>my_table</code> 的新表(如果它还不存在的话),然后向表中插入了一条记录。所有的这些操作都在安全的上下文中执行,无论操作成功还是遇到异常,数据库连接最终都会被正确关闭。</p>
|
|||
|
<h2 id="资源管理的最佳实践">资源管理的最佳实践<a aria-hidden="true" tabindex="-1" href="#资源管理的最佳实践" class="internal"> §</a></h2>
|
|||
|
<ul>
|
|||
|
<li><strong>及时释放资源</strong>:使用 <code>with</code> 语句确保文件或网络连接被及时释放。</li>
|
|||
|
<li><strong>异常安全</strong>:确保在资源管理器的 <code>__exit__</code> 方法中正确处理异常。</li>
|
|||
|
<li><strong>有效共享资源</strong>:在多线程/多进程环境中使用安全机制共享资源。</li>
|
|||
|
</ul></article></div><div class="right sidebar"><div class="graph "><h3>Graph View</h3><div class="graph-outer"><div id="graph-container" data-cfg="{"drag":true,"zoom":true,"depth":1,"scale":1.1,"repelForce":0.5,"centerForce":0.3,"linkDistance":30,"fontSize":0.6,"opacityScale":1,"showTags":true,"removeTags":[]}"></div><svg version="1.1" id="global-graph-icon" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 55 55" fill="currentColor" xmlSpace="preserve"><path d="M49,0c-3.309,0-6,2.691-6,6c0,1.035,0.263,2.009,0.726,2.86l-9.829,9.829C32.542,17.634,30.846,17,29,17
|
|||
|
s-3.542,0.634-4.898,1.688l-7.669-7.669C16.785,10.424,17,9.74,17,9c0-2.206-1.794-4-4-4S9,6.794,9,9s1.794,4,4,4
|
|||
|
c0.74,0,1.424-0.215,2.019-0.567l7.669,7.669C21.634,21.458,21,23.154,21,25s0.634,3.542,1.688,4.897L10.024,42.562
|
|||
|
C8.958,41.595,7.549,41,6,41c-3.309,0-6,2.691-6,6s2.691,6,6,6s6-2.691,6-6c0-1.035-0.263-2.009-0.726-2.86l12.829-12.829
|
|||
|
c1.106,0.86,2.44,1.436,3.898,1.619v10.16c-2.833,0.478-5,2.942-5,5.91c0,3.309,2.691,6,6,6s6-2.691,6-6c0-2.967-2.167-5.431-5-5.91
|
|||
|
v-10.16c1.458-0.183,2.792-0.759,3.898-1.619l7.669,7.669C41.215,39.576,41,40.26,41,41c0,2.206,1.794,4,4,4s4-1.794,4-4
|
|||
|
s-1.794-4-4-4c-0.74,0-1.424,0.215-2.019,0.567l-7.669-7.669C36.366,28.542,37,26.846,37,25s-0.634-3.542-1.688-4.897l9.665-9.665
|
|||
|
C46.042,11.405,47.451,12,49,12c3.309,0,6-2.691,6-6S52.309,0,49,0z M11,9c0-1.103,0.897-2,2-2s2,0.897,2,2s-0.897,2-2,2
|
|||
|
S11,10.103,11,9z M6,51c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S8.206,51,6,51z M33,49c0,2.206-1.794,4-4,4s-4-1.794-4-4
|
|||
|
s1.794-4,4-4S33,46.794,33,49z M29,31c-3.309,0-6-2.691-6-6s2.691-6,6-6s6,2.691,6,6S32.309,31,29,31z M47,41c0,1.103-0.897,2-2,2
|
|||
|
s-2-0.897-2-2s0.897-2,2-2S47,39.897,47,41z M49,10c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S51.206,10,49,10z"></path></svg></div><div id="global-graph-outer"><div id="global-graph-container" data-cfg="{"drag":true,"zoom":true,"depth":-1,"scale":0.9,"repelForce":0.5,"centerForce":0.3,"linkDistance":30,"fontSize":0.6,"opacityScale":1,"showTags":true,"removeTags":[]}"></div></div></div><div class="toc desktop-only"><button type="button" id="toc" class><h3>Table of Contents</h3><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="fold"><polyline points="6 9 12 15 18 9"></polyline></svg></button><div id="toc-content"><ul class="overflow"><li class="depth-0"><a href="#with-语句和上下文管理器的原理" data-for="with-语句和上下文管理器的原理">with 语句和上下文管理器的原理</a></li><li class="depth-0"><a href="#自定义资源管理" data-for="自定义资源管理">自定义资源管理</a></li><li class="depth-1"><a href="#自定义上下文管理器的实现" data-for="自定义上下文管理器的实现">自定义上下文管理器的实现</a></li><li class="depth-1"><a href="#contextlib-模块的应用" data-for="contextlib-模块的应用">contextlib 模块的应用</a></li><li class="depth-0"><a href="#高级应用" data-for="高级应用">高级应用</a></li><li class="depth-1"><a href="#在并发环境中的资源管理" data-for="在并发环境中的资源管理">在并发环境中的资源管理</a></li><li class="depth-1"><a href="#管理网络" data-for="管理网络">管理网络</a></li><li class="depth-1"><a href="#数据库连接" data-for="数据库连接">数据库连接</a></li><li class="depth-0"><a href="#资源管理的最佳实践" data-for="资源管理的最佳实践">资源管理的最佳实践</a></li></ul></div></div><div class="backlinks "><h3>Backlinks</h3><ul class="overflow"><li><a href="../../../../Tech/programming-language/Python/进阶/文件和IO操作" class="internal">文件和IO操作</a></li></ul></div><div class="explorer mobile-only"><button type="button" id="explorer" data-behavior="collapse" data-collapsed="collapsed" data-savestate="true" data-tree="[{"path":"Basics","collapsed":true},{"path":"Basics/english","collapsed":true},{"path":"Blog","collapsed":true},{"path":"Book","collapsed":true},{"path":"Book/个人成长","collapsed":true},{"path":"Book/医学健康","collapsed":true},{"path":"Book/历史","collapsed":true},{"path":"Book/哲学宗教","collapsed":true},{"path":"Book/心理","collapsed":true},{"path":"Book/政治军事","collapsed":true},{"path":"Book/教育学习","collapsed":true},{"path":"Book/文学","collapsed":true},{"path":"Book/生活百科","collapsed":true},{"path":"Book/社会文化","collapsed":true},{"path":"Book/科学技术","collapsed":true},{"path":"Book/经济理财","collapsed":true},{"path":"Book/艺术","collapsed":true},{"path":"Book/计算机","collapsed":true},{"path":"Company","collapsed":true},{"path":"Company/信息化","collapsed":true},{"path":"Company/信息化/规范","collapsed":true},{"path":"Culture","collapsed":true},{"path":"Government","collapsed":true},{"path":"
|
|||
|
function toggleCallout() {
|
|||
|
const outerBlock = this.parentElement;
|
|||
|
outerBlock.classList.toggle(`is-collapsed`);
|
|||
|
const collapsed = outerBlock.classList.contains(`is-collapsed`);
|
|||
|
const height = collapsed ? this.scrollHeight : outerBlock.scrollHeight;
|
|||
|
outerBlock.style.maxHeight = height + `px`;
|
|||
|
let current = outerBlock;
|
|||
|
let parent = outerBlock.parentElement;
|
|||
|
while (parent) {
|
|||
|
if (!parent.classList.contains(`callout`)) {
|
|||
|
return;
|
|||
|
}
|
|||
|
const collapsed2 = parent.classList.contains(`is-collapsed`);
|
|||
|
const height2 = collapsed2 ? parent.scrollHeight : parent.scrollHeight + current.scrollHeight;
|
|||
|
parent.style.maxHeight = height2 + `px`;
|
|||
|
current = parent;
|
|||
|
parent = parent.parentElement;
|
|||
|
}
|
|||
|
}
|
|||
|
function setupCallout() {
|
|||
|
const collapsible = document.getElementsByClassName(
|
|||
|
`callout is-collapsible`
|
|||
|
);
|
|||
|
for (const div of collapsible) {
|
|||
|
const title = div.firstElementChild;
|
|||
|
if (title) {
|
|||
|
title.removeEventListener(`click`, toggleCallout);
|
|||
|
title.addEventListener(`click`, toggleCallout);
|
|||
|
const collapsed = div.classList.contains(`is-collapsed`);
|
|||
|
const height = collapsed ? title.scrollHeight : div.scrollHeight;
|
|||
|
div.style.maxHeight = height + `px`;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
document.addEventListener(`nav`, setupCallout);
|
|||
|
window.addEventListener(`resize`, setupCallout);
|
|||
|
</script><script type="module">
|
|||
|
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs';
|
|||
|
const darkMode = document.documentElement.getAttribute('saved-theme') === 'dark'
|
|||
|
mermaid.initialize({
|
|||
|
startOnLoad: false,
|
|||
|
securityLevel: 'loose',
|
|||
|
theme: darkMode ? 'dark' : 'default'
|
|||
|
});
|
|||
|
document.addEventListener('nav', async () => {
|
|||
|
await mermaid.run({
|
|||
|
querySelector: '.mermaid'
|
|||
|
})
|
|||
|
});
|
|||
|
</script><script src="https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/contrib/copy-tex.min.js" type="application/javascript"></script><script src="../../../../postscript.js" type="module"></script></html>
|