import_platform_and_funcy_decorators_needmac_needlinux.py
· 1.5 KiB · Python
Ham
import platform
from funcy import decorator
@decorator
def need_mac(call):
"""檢查系統是否為 macOS,若不是則拋出異常。"""
if platform.system() != "Darwin":
raise Exception("This functionality is only supported in macOS")
return call()
@decorator
def need_linux(call):
"""檢查系統是否為 Linux,若不是則拋出異常。"""
if platform.system() != "Linux":
raise Exception("This functionality is only supported in Linux")
return call()
@decorator
def need_windows(call):
"""檢查系統是否為 Windows,若不是則拋出異常。"""
if platform.system() != "Windows":
raise Exception("This functionality is only supported in Windows")
return call()
@decorator
def need_unix(call):
"""檢查系統是否為 macOS 或 Linux,若不是則拋出異常。"""
if platform.system() not in ["Darwin", "Linux"]:
raise Exception("This functionality is only supported in macOS or Linux")
return call()
@need_unix
def foo():
"""測試函式,僅在 macOS 或 Linux 上執行。"""
print("Hello, world! (Running on macOS or Linux)")
@need_windows
def bar():
"""測試函式,僅在 Windows 上執行。"""
print("Hello, world! (Running on Windows)")
if __name__ == "__main__":
try:
foo() # 只有 macOS 和 Linux 可以執行
except Exception as e:
print(f"Error in foo(): {e}")
try:
bar() # 只有 Windows 可以執行
except Exception as e:
print(f"Error in bar(): {e}")
| 1 | import platform |
| 2 | from funcy import decorator |
| 3 | |
| 4 | @decorator |
| 5 | def 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 |
| 12 | def 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 |
| 19 | def 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 |
| 26 | def 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 |
| 33 | def foo(): |
| 34 | """測試函式,僅在 macOS 或 Linux 上執行。""" |
| 35 | print("Hello, world! (Running on macOS or Linux)") |
| 36 | |
| 37 | @need_windows |
| 38 | def bar(): |
| 39 | """測試函式,僅在 Windows 上執行。""" |
| 40 | print("Hello, world! (Running on Windows)") |
| 41 | |
| 42 | if __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 |