-
-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy pathdevmode.html
More file actions
508 lines (457 loc) · 35.7 KB
/
devmode.html
File metadata and controls
508 lines (457 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
<!DOCTYPE html>
<html lang="zh-TW" data-content_root="../">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Python 開發模式 — Python 3.14.5 說明文件</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
<link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=4365c8fe" />
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
<script src="../_static/documentation_options.js?v=8c54008b"></script>
<script src="../_static/doctools.js?v=9bcbadda"></script>
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="../_static/translations.js?v=cbf116e0"></script>
<script src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.14.5 說明文件 中搜尋"
href="../_static/opensearch.xml"/>
<link rel="author" title="關於這些文件" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜尋" href="../search.html" />
<link rel="copyright" title="版權所有" href="../copyright.html" />
<link rel="next" title="doctest --- 測試互動式 Python 範例" href="doctest.html" />
<link rel="prev" title="pydoc --- 文件產生器與線上幫助系統" href="pydoc.html" />
<link rel="canonical" href="https://docs.python.org/3/library/devmode.html">
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
<link rel="shortcut icon" type="image/png" href="../_static/py.svg">
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/menu.js"></script>
<script type="text/javascript" src="../_static/search-focus.js"></script>
<script type="text/javascript" src="../_static/themetoggle.js"></script>
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
<meta name="readthedocs-addons-api-version" content="1">
</head>
<body>
<div class="mobile-nav">
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
aria-pressed="false" aria-expanded="false" role="button" aria-label="選單">
<nav class="nav-content" role="navigation">
<label for="menuToggler" class="toggler__label">
<span></span>
</label>
<span class="nav-items-wrapper">
<a href="https://www.python.org/" class="nav-logo">
<img src="../_static/py.svg" alt="Python logo">
</a>
<span class="version_switcher_placeholder"></span>
<form role="search" class="search" action="../search.html" method="get">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
<path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
</svg>
<input placeholder="快速搜索" aria-label="快速搜索" type="search" name="q">
<input type="submit" value="前往">
</form>
</span>
</nav>
<div class="menu-wrapper">
<nav class="menu" role="navigation" aria-label="main navigation">
<div class="language_switcher_placeholder"></div>
<label class="theme-selector-label">
主題
<select class="theme-selector" oninput="activateTheme(this.value)">
<option value="auto" selected>自動</option>
<option value="light">淺色模式</option>
<option value="dark">深色模式</option>
</select>
</label>
<div>
<h3><a href="../contents.html">目錄</a></h3>
<ul>
<li><a class="reference internal" href="#">Python 開發模式</a><ul>
<li><a class="reference internal" href="#effects-of-the-python-development-mode">Python 開發模式的影響</a></li>
<li><a class="reference internal" href="#resourcewarning-example">ResourceWarning 範例</a></li>
<li><a class="reference internal" href="#bad-file-descriptor-error-example">檔案描述器的錯誤範例</a></li>
</ul>
</li>
</ul>
</div>
<div>
<h4>上個主題</h4>
<p class="topless"><a href="pydoc.html"
title="上一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code> --- 文件產生器與線上幫助系統</a></p>
</div>
<div>
<h4>下個主題</h4>
<p class="topless"><a href="doctest.html"
title="下一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code> --- 測試互動式 Python 範例</a></p>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const title = document.querySelector('meta[property="og:title"]').content;
const elements = document.querySelectorAll('.improvepage');
const pageurl = window.location.href.split('?')[0];
elements.forEach(element => {
const url = new URL(element.href.split('?')[0].replace("-nojs", ""));
url.searchParams.set('pagetitle', title);
url.searchParams.set('pageurl', pageurl);
url.searchParams.set('pagesource', "library/devmode.rst");
element.href = url.toString();
});
});
</script>
<div role="note" aria-label="source link">
<h3>此頁面</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">回報錯誤</a></li>
<li><a class="improvepage" href="../improve-page-nojs.html">改進此頁面</a></li>
<li>
<a href="https://github.com/python/cpython/blob/main/Doc/library/devmode.rst?plain=1"
rel="nofollow">顯示原始碼
</a>
</li>
<li>
<a href="https://github.com/python/python-docs-zh-TW/blob/3.14/library/devmode.po?plain=1"
rel="nofollow">顯示翻譯原始碼</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
<div class="related" role="navigation" aria-label="Related">
<h3>導航</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="總索引"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="doctest.html" title="doctest --- 測試互動式 Python 範例"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="pydoc.html" title="pydoc --- 文件產生器與線上幫助系統"
accesskey="P">上一頁</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li class="switchers">
<div class="language_switcher_placeholder"></div>
<div class="version_switcher_placeholder"></div>
</li>
<li>
</li>
<li id="cpython-language-and-version">
<a href="../index.html">3.14.5 Documentation</a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" >Python 標準函式庫 (Standard Library)</a> »</li>
<li class="nav-item nav-item-2"><a href="development.html" accesskey="U">開發工具</a> »</li>
<li class="nav-item nav-item-this"><a href="">Python 開發模式</a></li>
<li class="right">
<div class="inline-search" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="快速搜索" aria-label="快速搜索" type="search" name="q" id="search-box">
<input type="submit" value="前往">
</form>
</div>
|
</li>
<li class="right">
<label class="theme-selector-label">
主題
<select class="theme-selector" oninput="activateTheme(this.value)">
<option value="auto" selected>自動</option>
<option value="light">淺色模式</option>
<option value="dark">深色模式</option>
</select>
</label> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<section id="python-development-mode">
<span id="devmode"></span><h1>Python 開發模式<a class="headerlink" href="#python-development-mode" title="連結到這個標頭">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified added">在 3.7 版被加入.</span></p>
</div>
<p>Python 開發模式引入了額外的 runtime 檢查,預設啟用這些檢查的成本太高。如果程式碼正確,它不應比預設值更詳細;僅當偵測到問題時才會發出新警告。</p>
<p>可以使用 <a class="reference internal" href="../using/cmdline.html#cmdoption-X"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span> <span class="pre">dev</span></code></a> 命令列選項或將 <span class="target" id="index-12"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDEVMODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDEVMODE</span></code></a> 環境變數設為 1 來啟用它。</p>
<p>另請參閱 <a class="reference internal" href="../using/configure.html#debug-build"><span class="std std-ref">Python 除錯建置</span></a>。</p>
<section id="effects-of-the-python-development-mode">
<h2>Python 開發模式的影響<a class="headerlink" href="#effects-of-the-python-development-mode" title="連結到這個標頭">¶</a></h2>
<p>啟用 Python 開發模式類似以下指令,但具有如下所述的附加效果:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">PYTHONMALLOC</span><span class="o">=</span><span class="n">debug</span> <span class="n">PYTHONASYNCIODEBUG</span><span class="o">=</span><span class="mi">1</span> <span class="n">python</span> <span class="o">-</span><span class="n">W</span> <span class="n">default</span> <span class="o">-</span><span class="n">X</span> <span class="n">faulthandler</span>
</pre></div>
</div>
<p>Python 開發模式的效果:</p>
<ul>
<li><p>新增 <code class="docutils literal notranslate"><span class="pre">default</span></code> <a class="reference internal" href="warnings.html#describing-warning-filters"><span class="std std-ref">警告過濾器</span></a>。以下警告會被顯示:</p>
<ul class="simple">
<li><p><a class="reference internal" href="exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a></p></li>
<li><p><a class="reference internal" href="exceptions.html#ImportWarning" title="ImportWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportWarning</span></code></a></p></li>
<li><p><a class="reference internal" href="exceptions.html#PendingDeprecationWarning" title="PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a></p></li>
<li><p><a class="reference internal" href="exceptions.html#ResourceWarning" title="ResourceWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceWarning</span></code></a></p></li>
</ul>
<p>一般來說,上述警告會被預設的<a class="reference internal" href="warnings.html#describing-warning-filters"><span class="std std-ref">警告過濾器</span></a>給過濾掉。</p>
<p>它的行為就像使用 <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span> <span class="pre">default</span></code></a> 命令列選項一樣。</p>
<p>使用 <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span> <span class="pre">error</span></code></a> 命令列選項或將 <span class="target" id="index-13"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONWARNINGS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONWARNINGS</span></code></a> 環境變數設為 <code class="docutils literal notranslate"><span class="pre">error</span></code> 會將警告視為錯誤。</p>
</li>
<li><p>在記憶體分配器上安裝除錯 hook(掛鉤)以檢查:</p>
<ul class="simple">
<li><p>緩衝區下溢 (underflow)</p></li>
<li><p>緩衝區溢位 (overflow)</p></li>
<li><p>記憶體分配器 API 違規</p></li>
<li><p>GIL 的不安全使用</p></li>
</ul>
<p>請參閱 <a class="reference internal" href="../c-api/memory.html#c.PyMem_SetupDebugHooks" title="PyMem_SetupDebugHooks"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_SetupDebugHooks()</span></code></a> C 函式。</p>
<p>它的行為就好像是將 <span class="target" id="index-14"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONMALLOC"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONMALLOC</span></code></a> 環境變數設定為 <code class="docutils literal notranslate"><span class="pre">debug</span></code> 一樣。</p>
<p>若要啟用 Python 開發模式而不在記憶體分配器上安裝偵錯 hook,請將 <span class="target" id="index-15"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONMALLOC"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONMALLOC</span></code></a> 環境變數設為 <code class="docutils literal notranslate"><span class="pre">default</span></code>。</p>
</li>
<li><p>在 Python 啟動時呼叫 <a class="reference internal" href="faulthandler.html#faulthandler.enable" title="faulthandler.enable"><code class="xref py py-func docutils literal notranslate"><span class="pre">faulthandler.enable()</span></code></a> 來為 <a class="reference internal" href="signal.html#signal.SIGSEGV" title="signal.SIGSEGV"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGSEGV</span></code></a>、<a class="reference internal" href="signal.html#signal.SIGFPE" title="signal.SIGFPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGFPE</span></code></a>、<a class="reference internal" href="signal.html#signal.SIGABRT" title="signal.SIGABRT"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGABRT</span></code></a>、<a class="reference internal" href="signal.html#signal.SIGBUS" title="signal.SIGBUS"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGBUS</span></code></a> 和 <a class="reference internal" href="signal.html#signal.SIGILL" title="signal.SIGILL"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGILL</span></code></a> 訊號安裝處理函式以在當機時傾印 (dump) Python 回溯 (traceback)。</p>
<p>它的行為就像使用 <a class="reference internal" href="../using/cmdline.html#cmdoption-X"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span> <span class="pre">faulthandler</span></code></a> 命令列選項或將 <span class="target" id="index-16"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONFAULTHANDLER"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONFAULTHANDLER</span></code></a> 環境變數設定為 <code class="docutils literal notranslate"><span class="pre">1</span></code>。</p>
</li>
<li><p>啟用 <a class="reference internal" href="asyncio-dev.html#asyncio-debug-mode"><span class="std std-ref">asyncio 除錯模式</span></a>。例如 <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> 會檢查未被等待的 (not awaited) 協程並記錄 (log) 它們。</p>
<p>它的行為就像將 <span class="target" id="index-17"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONASYNCIODEBUG"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONASYNCIODEBUG</span></code></a> 環境變數設定為 1 一樣。</p>
</li>
<li><p>檢查字串編碼和解碼操作的 <em>encoding</em> 和 <em>errors</em> 引數。例如:<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>、<a class="reference internal" href="stdtypes.html#str.encode" title="str.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.encode()</span></code></a> 和 <a class="reference internal" href="stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.decode()</span></code></a>。</p>
<p>預設情況下,為了獲得最佳效能,僅在第一個編碼/解碼錯誤時檢查 <em>errors</em> 引數,並且有時會因為是空字串而忽略 <em>encoding</em> 引數。</p>
</li>
<li><p><a class="reference internal" href="io.html#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.IOBase</span></code></a> 解構函式會記錄 <code class="docutils literal notranslate"><span class="pre">close()</span></code> 例外。</p></li>
<li><p>將 <a class="reference internal" href="sys.html#sys.flags" title="sys.flags"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.flags</span></code></a> 的 <a class="reference internal" href="sys.html#sys.flags.dev_mode" title="sys.flags.dev_mode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dev_mode</span></code></a> 屬性設為 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p></li>
</ul>
<p>Python 開發模式預設不會啟用 <a class="reference internal" href="tracemalloc.html#module-tracemalloc" title="tracemalloc: Trace memory allocations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tracemalloc</span></code></a> 模組,因為(效能和記憶體的)開銷太大。啟用 <a class="reference internal" href="tracemalloc.html#module-tracemalloc" title="tracemalloc: Trace memory allocations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tracemalloc</span></code></a> 模組可提供有關某些錯誤來源的附加資訊。例如 <a class="reference internal" href="exceptions.html#ResourceWarning" title="ResourceWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceWarning</span></code></a> 記錄了分配資源之處的回溯、緩衝區溢位錯誤記錄了分配記憶體區塊的回溯。</p>
<p>Python 開發模式不會防止 <a class="reference internal" href="../using/cmdline.html#cmdoption-O"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> 命令列選項刪除 <a class="reference internal" href="../reference/simple_stmts.html#assert"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code></a> 陳述式,也不會防止將 <a class="reference internal" href="constants.html#debug__" title="__debug__"><code class="xref py py-const docutils literal notranslate"><span class="pre">__debug__</span></code></a> 設定為 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<p>Python 開發模式只能在 Python 啟動時啟用。它的值可以從 <a class="reference internal" href="sys.html#sys.flags" title="sys.flags"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.flags.dev_mode</span></code></a> 讀取。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版的變更: </span><a class="reference internal" href="io.html#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.IOBase</span></code></a> 解構函式現在會記錄 <code class="docutils literal notranslate"><span class="pre">close()</span></code> 例外。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.9 版的變更: </span>現在會為字串編碼和解碼操作檢查 <em>encoding</em> 和 <em>errors</em> 引數。</p>
</div>
</section>
<section id="resourcewarning-example">
<h2>ResourceWarning 範例<a class="headerlink" href="#resourcewarning-example" title="連結到這個標頭">¶</a></h2>
<p>計算命令列中指定的文字檔案列數的腳本範例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
<span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>
<span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="n">nlines</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">readlines</span><span class="p">())</span>
<span class="nb">print</span><span class="p">(</span><span class="n">nlines</span><span class="p">)</span>
<span class="c1"># The file is closed implicitly</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span>
<span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>該腳本不會明確關閉檔案。預設情況下,Python 不會發出任何警告。使用 README.txt 的範例,該檔案有 269 列:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>script.py<span class="w"> </span>README.txt
<span class="go">269</span>
</pre></div>
</div>
<p>啟用 Python 開發模式會顯示 <a class="reference internal" href="exceptions.html#ResourceWarning" title="ResourceWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceWarning</span></code></a> 警告:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-X<span class="w"> </span>dev<span class="w"> </span>script.py<span class="w"> </span>README.txt
<span class="go">269</span>
<span class="go">script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'></span>
<span class="go"> main()</span>
<span class="go">ResourceWarning: Enable tracemalloc to get the object allocation traceback</span>
</pre></div>
</div>
<p>此外,啟用 <a class="reference internal" href="tracemalloc.html#module-tracemalloc" title="tracemalloc: Trace memory allocations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tracemalloc</span></code></a> 會顯示檔案被開啟的那一列:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-X<span class="w"> </span>dev<span class="w"> </span>-X<span class="w"> </span><span class="nv">tracemalloc</span><span class="o">=</span><span class="m">5</span><span class="w"> </span>script.py<span class="w"> </span>README.rst
<span class="go">269</span>
<span class="go">script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'></span>
<span class="go"> main()</span>
<span class="go">Object allocated at (most recent call last):</span>
<span class="go"> File "script.py", lineno 10</span>
<span class="go"> main()</span>
<span class="go"> File "script.py", lineno 4</span>
<span class="go"> fp = open(sys.argv[1])</span>
</pre></div>
</div>
<p>修復方法是明確關閉該檔案。以下是使用情境管理器的範例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>
<span class="c1"># 在退出 with 區塊時明確關閉檔案</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
<span class="n">nlines</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">readlines</span><span class="p">())</span>
<span class="nb">print</span><span class="p">(</span><span class="n">nlines</span><span class="p">)</span>
</pre></div>
</div>
<p>不明確關閉資源可能會使資源開啟的時間比預期的長得多;它可能會在退出 Python 時導致嚴重問題。在 CPython 中很糟糕,但在 PyPy 中更糟。明確關閉資源使應用程式更具確定性和可靠性。</p>
</section>
<section id="bad-file-descriptor-error-example">
<h2>檔案描述器的錯誤範例<a class="headerlink" href="#bad-file-descriptor-error-example" title="連結到這個標頭">¶</a></h2>
<p>顯示自身第一列的腳本:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">os</span>
<span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>
<span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="vm">__file__</span><span class="p">)</span>
<span class="n">firstline</span> <span class="o">=</span> <span class="n">fp</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="n">firstline</span><span class="o">.</span><span class="n">rstrip</span><span class="p">())</span>
<span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">fileno</span><span class="p">())</span>
<span class="c1"># 檔案是隱式關閉的</span>
<span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>預設情況下,Python 不會發出任何警告:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>script.py
<span class="go">import os</span>
</pre></div>
</div>
<p>Python 開發模式在最終化 (finalize) 檔案物件時顯示 <a class="reference internal" href="exceptions.html#ResourceWarning" title="ResourceWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceWarning</span></code></a> 並記錄 "Bad file descriptor" 錯誤:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-X<span class="w"> </span>dev<span class="w"> </span>script.py
<span class="go">import os</span>
<span class="go">script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'></span>
<span class="go"> main()</span>
<span class="go">ResourceWarning: Enable tracemalloc to get the object allocation traceback</span>
<span class="go">Exception ignored in: <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'></span>
<span class="go">Traceback (most recent call last):</span>
<span class="go"> File "script.py", line 10, in <module></span>
<span class="go"> main()</span>
<span class="go">OSError: [Errno 9] Bad file descriptor</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">os.close(fp.fileno())</span></code> 會關閉檔案描述器。當檔案物件最終化函式 (finalizer) 嘗試再次關閉檔案描述器時,它會失敗並出現 <code class="docutils literal notranslate"><span class="pre">Bad</span> <span class="pre">file</span> <span class="pre">descriptor</span></code> 錯誤。檔案描述器只能關閉一次。在最壞的情況下,將它關閉兩次可能會導致崩潰 (crash)(相關範例請參閱 <a class="reference external" href="https://bugs.python.org/issue?@action=redirect&bpo=18748">bpo-18748</a>)。</p>
<p>修復方法是刪除 <code class="docutils literal notranslate"><span class="pre">os.close(fp.fileno())</span></code> 那列,或使用 <code class="docutils literal notranslate"><span class="pre">closefd=False</span></code> 開啟檔案。</p>
</section>
</section>
<div class="clearer"></div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="Main">
<div class="sphinxsidebarwrapper">
<div>
<h3><a href="../contents.html">目錄</a></h3>
<ul>
<li><a class="reference internal" href="#">Python 開發模式</a><ul>
<li><a class="reference internal" href="#effects-of-the-python-development-mode">Python 開發模式的影響</a></li>
<li><a class="reference internal" href="#resourcewarning-example">ResourceWarning 範例</a></li>
<li><a class="reference internal" href="#bad-file-descriptor-error-example">檔案描述器的錯誤範例</a></li>
</ul>
</li>
</ul>
</div>
<div>
<h4>上個主題</h4>
<p class="topless"><a href="pydoc.html"
title="上一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code> --- 文件產生器與線上幫助系統</a></p>
</div>
<div>
<h4>下個主題</h4>
<p class="topless"><a href="doctest.html"
title="下一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code> --- 測試互動式 Python 範例</a></p>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const title = document.querySelector('meta[property="og:title"]').content;
const elements = document.querySelectorAll('.improvepage');
const pageurl = window.location.href.split('?')[0];
elements.forEach(element => {
const url = new URL(element.href.split('?')[0].replace("-nojs", ""));
url.searchParams.set('pagetitle', title);
url.searchParams.set('pageurl', pageurl);
url.searchParams.set('pagesource', "library/devmode.rst");
element.href = url.toString();
});
});
</script>
<div role="note" aria-label="source link">
<h3>此頁面</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">回報錯誤</a></li>
<li><a class="improvepage" href="../improve-page-nojs.html">改進此頁面</a></li>
<li>
<a href="https://github.com/python/cpython/blob/main/Doc/library/devmode.rst?plain=1"
rel="nofollow">顯示原始碼
</a>
</li>
<li>
<a href="https://github.com/python/python-docs-zh-TW/blob/3.14/library/devmode.po?plain=1"
rel="nofollow">顯示翻譯原始碼</a>
</li>
</ul>
</div>
</div>
<div id="sidebarbutton" title="收合側邊欄">
<span>«</span>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="Related">
<h3>導航</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="總索引"
>索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="doctest.html" title="doctest --- 測試互動式 Python 範例"
>下一頁</a> |</li>
<li class="right" >
<a href="pydoc.html" title="pydoc --- 文件產生器與線上幫助系統"
>上一頁</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li class="switchers">
<div class="language_switcher_placeholder"></div>
<div class="version_switcher_placeholder"></div>
</li>
<li>
</li>
<li id="cpython-language-and-version">
<a href="../index.html">3.14.5 Documentation</a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" >Python 標準函式庫 (Standard Library)</a> »</li>
<li class="nav-item nav-item-2"><a href="development.html" >開發工具</a> »</li>
<li class="nav-item nav-item-this"><a href="">Python 開發模式</a></li>
<li class="right">
<div class="inline-search" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="快速搜索" aria-label="快速搜索" type="search" name="q" id="search-box">
<input type="submit" value="前往">
</form>
</div>
|
</li>
<li class="right">
<label class="theme-selector-label">
主題
<select class="theme-selector" oninput="activateTheme(this.value)">
<option value="auto" selected>自動</option>
<option value="light">淺色模式</option>
<option value="dark">深色模式</option>
</select>
</label> |</li>
</ul>
</div>
<div class="footer">
© <a href="../copyright.html">版權所有</a> 2001 Python Software Foundation.
<br>
此頁面採用 Python 軟體基金會授權條款第 2 版。
<br>
文件中的範例、應用技巧與其他程式碼額外採用了 Zero Clause BSD 授權條款。
<br>
更多訊息請見<a href="/license.html">歷史與授權條款</a>。<br>
<br>
Python 軟體基金會是一家非營利法人。
<a href="https://www.python.org/psf/donations/">敬請捐贈。</a>
<br>
<br>
最後更新於 5月 14, 2026 (19:12 UTC)。
<a href="/bugs.html">發現 bug</a>?
<br>
以 <a href="https://www.sphinx-doc.org/">Sphinx</a>8.2.3建立。
</div>
</body>
</html>