custom_context_example.py
· 312 B · Python
Неформатований
from contextlib import contextmanager
@contextmanager
def custom_context(name):
print(f"進入上下文: {name}")
try:
yield name # 提供資源
finally:
print(f"退出上下文: {name}")
# 使用 with 語法
with custom_context("示範") as ctx:
print(f"內部執行: {ctx}")
| 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}") |
| 14 |
custom_file_context_manager.py
· 390 B · Python
Неформатований
from contextlib import contextmanager
@contextmanager
def open_file(file_path, mode):
file = open(file_path, mode)
try:
yield file # 提供檔案資源
finally:
file.close() # 確保檔案關閉
print(f"檔案 {file_path} 已關閉")
# 使用自訂上下文管理器
with open_file("example.txt", "w") as f:
f.write("這是一個測試檔案\n")
| 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") |
| 15 |
thread_lock_context_manager.py
· 326 B · Python
Неформатований
from contextlib import contextmanager
import threading
lock = threading.Lock()
@contextmanager
def locked_resource():
print("獲取鎖")
lock.acquire()
try:
yield
finally:
lock.release()
print("釋放鎖")
# 測試鎖機制
with locked_resource():
print("執行臨界區程式")
| 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("執行臨界區程式") |
| 19 |