This article mainly introduces how to use the decorator and thread to limit the execution time of functions in python. it mainly involves the use of timelimited functions and is of great practical value, for more information about how to use the decorator and thread to limit the function execution time, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
In many cases, a function contains unpredictable tasks, such as calling other software to capture information from the network. a function may be stuck somewhere, this code can be used to limit the execution time of a function. you only need to add a decorator above the function. timelimited (2) can limit that the function must be executed within 2 seconds, if the execution is complete, the normal return value of the function is returned. if the execution times out, an error message is thrown.
#-*-Coding: UTF-8-*-from threading import Threadimport timeclass TimeoutException (Exception): passThreadStop = Thread. _ Thread _ stop # obtain the private function def timelimited (timeout): def decorator (function): def decorator2 (* args, ** kwargs): class TimeLimited (Thread ): def _ init _ (self, _ error = None,): Thread. _ init _ (self) self. _ error = _ error def run (self): try: self. result = function (* args, ** kwargs) except T Exception, e: self. _ error = e def _ stop (self): if self. isAlive (): ThreadStop (self) t = TimeLimited () t. start () t. join (timeout) if isinstance (t. _ error, TimeoutException): t. _ stop () raise TimeoutException ('timeout for % s' % (repr (function) if t. isAlive (): t. _ stop () raise TimeoutException ('timeout for % s' % (repr (function) if t. _ error is None: return t. result return decorator2 return decorator @ timelimited (2) def fn_1 (secs): time. sleep (secs) return 'finished' if _ name _ = "_ main _": print fn_1 (4)
I hope this article will help you with Python programming.