The examples in this article describe how Python uses adorners and threads to limit function execution time. Share to everyone for your reference. The specific analysis is as follows:
Most of the time the function contains some unpredictable things, such as invoking other software, crawling information from the network, perhaps a function will be stuck in a place of the dynamic, this code can be used to limit the execution time of the function, just add an adorner above the function, timelimited (2) You can qualify that the function must be completed in 2 seconds, return the normal return value of the function if the execution completes, and throw an error message if the execution times out.
#-*-Coding:utf-8-*-from threading import Thread Import Time Class TimeoutException (Exception): Pass threadstop = T
hread._thread__stop# Get 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 except
Ion,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 are None:return t.result return decor Ator2 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 your Python programming.