本章給大家在項目使用時候,常見的一種情況解決案例,即是當我們調(diào)用多個線程,使用了同一個函數(shù)去處理數(shù)據(jù)的時候,有些用函數(shù)已經(jīng)處理完成,但是有些還沒有,這就需要我們將任務(wù)進行分割,然后當一小部分任務(wù)執(zhí)行后,退出來,另外沒有執(zhí)行的完成超時的就繼續(xù)去執(zhí)行,下面就針對遇到這些問題的小伙伴,給大家提供解決參考。
安裝timeout-decorator庫:
1
|
pip3 install timeout - decorator |
編寫異常語句:
1
|
@timeout_decorator .timeout( 5 , timeout_exception = StopIteration) |
函數(shù)限制超時:
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() |
到此這篇關(guān)于python函數(shù)超時自動退出的實操方法的文章就介紹到這了,更多相關(guān)python函數(shù)超時怎么自動退出內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.py.cn/jishu/jichu/22286.html