本章給大家在項目使用時候,常見的一種情況解決案例,即是當我們調用多個線程,使用了同一個函數去處理數據的時候,有些用函數已經處理完成,但是有些還沒有,這就需要我們將任務進行分割,然后當一小部分任務執行后,退出來,另外沒有執行的完成超時的就繼續去執行,下面就針對遇到這些問題的小伙伴,給大家提供解決參考。
安裝timeout-decorator庫:
1
|
pip3 install timeout - decorator |
編寫異常語句:
1
|
@timeout_decorator .timeout( 5 , timeout_exception = StopIteration) |
函數限制超時:
1
|
@timeout_decorator .timeout( 5 , use_signals = False ) |
解決案例:
1
2
3
4
5
6
7
8
9
10
11
|
import timeout_decorator @timeout_decorator .timeout( 5 ) def mytest(): print ( "Start" ) for i in range ( 1 , 10 ): time.sleep( 1 ) print ( "{} seconds have passed" . format (i)) def main(): mytest() if __name__ = = '__main__' : main() |
到此這篇關于python函數超時自動退出的實操方法的文章就介紹到這了,更多相關python函數超時怎么自動退出內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.py.cn/jishu/jichu/22286.html