「Python實用秘技02」給Python函數定「鬧鐘」
- 2021 年 12 月 11 日
- 筆記
- Python實用秘技
本文完整示例程式碼及文件已上傳至我的
Github
倉庫//github.com/CNFeffery/PythonPracticalSkills
這是我的系列文章「Python實用秘技」的第2期,本系列立足於筆者日常工作中使用Python
輔助辦公的心得體會,每一期為大家帶來一個3分鐘即可學會的簡單小技巧。
作為系列第2期,我們即將學習的是:為Python函數添加執行超時檢查功能
。

某些常用的庫如requests
的get()
函數,具有特定的參數timeout
,設置後可以在其運行超過一定時間還沒運行完成時拋出超時錯誤。
而如果我們想為自定義函數也添加類似的「鬧鐘」超時檢查功能,最簡單的方式是使用第三方庫wrapt_timeout_decorator
中的timeout()
裝飾器,通過參數傳遞超時時長(單位:秒)即可,下面是一個簡單的例子:
from wrapt_timeout_decorator import timeout
@timeout(5) # 設置超時時長為5秒
def demo_func(seconds: float) -> float:
# 此處time在函數中導入是為了繞開jupyter中wrapt_timeout_decorator與time模組的特殊錯誤
# 詳見//github.com/bitranox/wrapt_timeout_decorator/issues/24
import time
time.sleep(seconds)
return seconds
# 未超時時正常運行
demo_func(3)
# 超時報錯
demo_func(6)

並且不只是函數,類中的靜態方法亦可使用:
class Demo:
@timeout(5) # 設置超時時長為5秒
@staticmethod
def demo_func(seconds: float) -> float:
# 此處time在函數中導入是為了繞開jupyter中wrapt_timeout_decorator與time模組的特殊錯誤
# 詳見//github.com/bitranox/wrapt_timeout_decorator/issues/24
import time
time.sleep(seconds)
return seconds
demo = Demo()
demo.demo_func(3)
Demo().demo_func(6)

使用場景非常之多,譬如前不久筆者就用它來解決fabric
模擬執行nohup
命令時的持續阻塞問題。
本期分享結束,咱們下回見~👋