Utoljára aktív 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 捕捉例外,若目前作業系統不符合要求,則輸出相應錯誤訊息。這樣的設計有助於確保平台專屬功能在正確的環境中執行,避免跨平台錯誤。

Revízió d49fe5a5ae4e8a2b8fc18359ec7b1435d52c0d35

import_platform_and_funcy_decorators_needmac_needlinux.py Eredeti
1import platform
2from funcy import decorator
3
4@decorator
5def need_mac(call):
6 """檢查系統是否為 macOS,若不是則拋出異常。"""
7 if platform.system() != "Darwin":
8 raise Exception("This functionality is only supported in macOS")
9 return call()
10
11@decorator
12def need_linux(call):
13 """檢查系統是否為 Linux,若不是則拋出異常。"""
14 if platform.system() != "Linux":
15 raise Exception("This functionality is only supported in Linux")
16 return call()
17
18@decorator
19def need_windows(call):
20 """檢查系統是否為 Windows,若不是則拋出異常。"""
21 if platform.system() != "Windows":
22 raise Exception("This functionality is only supported in Windows")
23 return call()
24
25@decorator
26def need_unix(call):
27 """檢查系統是否為 macOS 或 Linux,若不是則拋出異常。"""
28 if platform.system() not in ["Darwin", "Linux"]:
29 raise Exception("This functionality is only supported in macOS or Linux")
30 return call()
31
32@need_unix
33def foo():
34 """測試函式,僅在 macOS 或 Linux 上執行。"""
35 print("Hello, world! (Running on macOS or Linux)")
36
37@need_windows
38def bar():
39 """測試函式,僅在 Windows 上執行。"""
40 print("Hello, world! (Running on Windows)")
41
42if __name__ == "__main__":
43 try:
44 foo() # 只有 macOS 和 Linux 可以執行
45 except Exception as e:
46 print(f"Error in foo(): {e}")
47
48 try:
49 bar() # 只有 Windows 可以執行
50 except Exception as e:
51 print(f"Error in bar(): {e}")
52