python防止程序超時的實現(xiàn)示例
因為某個需求,需要在程序運行的時候防止超時。在網(wǎng)上搜了以下發(fā)現(xiàn)有3種方法
1.@func_set_timeout這個注解
實測可以用,但是用起來比較麻煩,因為這個超時后會跑出異常,可以直接注解在函數(shù)上但不能注解在單條語句上,我設想的是把超時和異常同時處理,這個會拋出新的異常不太符合我的需求
# func_set_timeout作為裝飾器使用,來作為目標函數(shù)的超時處理方式 import time import os from func_timeout import func_set_timeout @func_set_timeout(5) def my_test(name): print('子進程運行中,name={},pid={}'.format(name, os.getpid())) time.sleep(4) print('子進程已經(jīng)結(jié)束') if __name__ == '__main__': print('父進程:{}'.format(os.getpid())) try: p = Process(target=my_test, args=('test', )) p.start() except TimeoutError as e: print('子程序超時')
2.多進程/多限制的.join
比如下面的代碼
import time import threading def worker(): print('worker start') time.sleep(10) print('worker end') t = threading.Thread(target=worker) t.start() # 等待線程結(jié)束,不能超過5秒 t.join(5) if t.is_alive(): print('worker overtime') else: print('worker finished')
實測發(fā)現(xiàn)運行結(jié)果是這樣,到了5秒提示overtime但是程序繼續(xù)運行,然后到了10秒程序運行結(jié)束,雖然有超時的效果但是和我設想的還是有區(qū)別,我想的是時間到了你就別繼續(xù)運行了
3.使用eventlet.Timeout來實現(xiàn)
實測下來這個是最符合我需求的,時間到了直接跳出,加一個timeout的變量就能知道是否超時了。美中不足就是必須加一條語句,eventlet.monkey_patch(),簡單搜索了下發(fā)現(xiàn)這個屬于程序在運行時動態(tài)對已有代碼進行修改,而不需要修改原始代碼的一個熱補丁。
使用了eventlet后,同時處理超時和異常的代碼如下
""" 用于處理函數(shù)超時的情況,同時記錄程序異常 """ import eventlet class PyTimer: """ 用于在處理異常的同時防止程序超時 """ def __init__(self, max_time=5): """ 初始化 """ # 必須有這條代碼 eventlet.monkey_patch() self.errors = "" # 最大超時的秒數(shù) self.max_time = max_time def set_max_time(self,new_time): """ 設置新的超時秒數(shù) """ self.max_time=new_time def count_time(self, function, *args): """ 運行函數(shù),記錄異常,同時超時跳出 """ return_result = None timeout = True current_error = "" try: with eventlet.Timeout(self.max_time, False): # 設置超時時間為5秒 return_result = function(*args) timeout = False except Exception as e: current_error = str(e) + "\n" finally: if timeout: current_error += function.__name__ + "超時\n" print(current_error) self.errors += current_error return return_result def get_errors(self): """ 獲取報錯信息 """ return self.errors if __name__ == '__main__': def long_fun(a, b): import time print(a, b) time.sleep(20) my_timer = PyTimer() my_timer.count_time(long_fun, 1, 2)
到此這篇關于python防止程序超時的實現(xiàn)示例的文章就介紹到這了,更多相關python防止程序超時內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python字符串內(nèi)置函數(shù)功能與用法總結(jié)
這篇文章主要介紹了Python字符串內(nèi)置函數(shù)功能與用法,結(jié)合實例形式總結(jié)分析了Python常見字符串操作函數(shù)的功能、分類、使用方法及相關操作注意事項,需要的朋友可以參考下2019-04-04