Ultima attività 10 months ago

這段 Python 程式碼利用 funcy 模組的裝飾器來 檢查目前作業系統,從而限制某些函式僅在特定平台上執行。具體來說,need_mac、need_linux、need_windows 與 need_unix 分別用來檢查是否在 macOS、Linux、Windows 或 Unix(macOS 或 Linux)系統上執行;函式 foo() 被 @need_unix 裝飾,僅允許在 Unix 系統上執行,而函式 bar() 則僅允許在 Windows 系統上執行。主程式透過 try-except 捕捉例外,若目前作業系統不符合要求,則輸出相應錯誤訊息。這樣的設計有助於確保平台專屬功能在正確的環境中執行,避免跨平台錯誤。

Revisione ca87e6782a115dbb66fe8c23ee9aa6faa2bf4147

import_platform_and_funcy_decorators_needmac_needlinux.py Raw
1import platform # 匯入 platform 模組
2
3from funcy import decorator # 匯入 funcy 模組中的 decorator 裝飾器
4
5@decorator
6def needmac(call):
7 """檢查系統是否為 macOS,若不是則拋出異常。"""
8 if platform.system() != "Darwin":
9 raise Exception(
10 "The system is not macOS. " "This functionality only supported in macOS"
11 )
12
13 return call()
14
15@decorator
16def needlinux(call):
17 """檢查系統是否為 Linux,若不是則拋出異常。"""
18 if platform.system() != "Linux":
19 raise Exception(
20 "The system is not Linux. " "This functionality only supported in Linux"
21 )
22
23 return call()
24
25@needmac # 裝飾器:需要 macOS 系統
26@needlinux # 裝飾器:需要 Linux 系統
27def foo():
28 """一個測試函式,若系統為 macOS 或 Linux,則印出 'Hello, world!'"""
29 print("Hello, world!")
30
31foo() # 呼叫函式
32