Последняя активность 9 months ago

contextlib.contextmanager 可用於建立自訂的 with 語句上下文管理器,適用於 資源管理(如檔案、資料庫連線、鎖定機制),確保進入與退出時執行適當的操作。

Версия fd270c8cb0bbc2a034a046b02e7f4ee9e0c71298

custom_context_example.py Исходник
1from contextlib import contextmanager
2
3@contextmanager
4def custom_context(name):
5 print(f"進入上下文: {name}")
6 try:
7 yield name # 提供資源
8 finally:
9 print(f"退出上下文: {name}")
10
11# 使用 with 語法
12with custom_context("示範") as ctx:
13 print(f"內部執行: {ctx}")
14
custom_file_context_manager.py Исходник
1from contextlib import contextmanager
2
3@contextmanager
4def open_file(file_path, mode):
5 file = open(file_path, mode)
6 try:
7 yield file # 提供檔案資源
8 finally:
9 file.close() # 確保檔案關閉
10 print(f"檔案 {file_path} 已關閉")
11
12# 使用自訂上下文管理器
13with open_file("example.txt", "w") as f:
14 f.write("這是一個測試檔案\n")
15
thread_lock_context_manager.py Исходник
1from contextlib import contextmanager
2import threading
3
4lock = threading.Lock()
5
6@contextmanager
7def locked_resource():
8 print("獲取鎖")
9 lock.acquire()
10 try:
11 yield
12 finally:
13 lock.release()
14 print("釋放鎖")
15
16# 測試鎖機制
17with locked_resource():
18 print("執行臨界區程式")
19