Utoljára aktív 9 months ago

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

timmy gist felülvizsgálása 9 months ago. Revízióhoz ugrás

3 files changed, 45 insertions

custom_context_example.py(fájl létrehozva)

@@ -0,0 +1,13 @@
1 + from contextlib import contextmanager
2 +
3 + @contextmanager
4 + def custom_context(name):
5 + print(f"進入上下文: {name}")
6 + try:
7 + yield name # 提供資源
8 + finally:
9 + print(f"退出上下文: {name}")
10 +
11 + # 使用 with 語法
12 + with custom_context("示範") as ctx:
13 + print(f"內部執行: {ctx}")

custom_file_context_manager.py(fájl létrehozva)

@@ -0,0 +1,14 @@
1 + from contextlib import contextmanager
2 +
3 + @contextmanager
4 + def 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 + # 使用自訂上下文管理器
13 + with open_file("example.txt", "w") as f:
14 + f.write("這是一個測試檔案\n")

thread_lock_context_manager.py(fájl létrehozva)

@@ -0,0 +1,18 @@
1 + from contextlib import contextmanager
2 + import threading
3 +
4 + lock = threading.Lock()
5 +
6 + @contextmanager
7 + def locked_resource():
8 + print("獲取鎖")
9 + lock.acquire()
10 + try:
11 + yield
12 + finally:
13 + lock.release()
14 + print("釋放鎖")
15 +
16 + # 測試鎖機制
17 + with locked_resource():
18 + print("執行臨界區程式")
Újabb Régebbi