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