「Python實用秘技02」給Python函數(shù)定“鬧鐘”

添加微信號"CNFeffery"加入技術交流群
?本文完整示例代碼及文件已上傳至我的
?Github倉庫https://github.com/CNFeffery/PythonPracticalSkills
這是我的系列文章**「Python實用秘技」「的第2期,本系列立足于筆者日常工作中使用Python輔助辦公的心得體會,每一期為大家?guī)硪粋€」3分鐘**即可學會的簡單小技巧。
作為系列第2期,我們即將學習的是:為Python函數(shù)添加執(zhí)行超時檢查功能。

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

并且不只是函數(shù),類中的靜態(tài)方法亦可使用:
class?Demo:
????
????@timeout(5)?#?設置超時時長為5秒
????@staticmethod
????def?demo_func(seconds:?float)?->?float:
????????#?此處time在函數(shù)中導入是為了繞開jupyter中wrapt_timeout_decorator與time模塊的特殊錯誤
????????#?詳見https://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模擬執(zhí)行nohup命令時的持續(xù)阻塞問題。
本期分享結束,咱們下回見~??

加入知識星球【我們談論數(shù)據(jù)科學】
400+小伙伴一起學習!
· 推薦閱讀?·
評論
圖片
表情
