The examples in this article describe how Python uses adorners and threads to limit the execution time of functions. Share to everyone for your reference. The specific analysis is as follows:
Many times inside the function contains some unpredictable things, such as invoking other software, crawling information from the network, maybe a function will be stuck somewhere is not dynamic, this code can be used to limit the execution time of the function, only need to add an adorner above the function, timelimited (2) You can limit the function to complete within 2 seconds, and return the function's normal return value if execution completes, and throw an error message if the execution times out.
#-*-Coding:utf-8-*-from Threading Import Threadimport timeclass timeoutexception (Exception): Passthreadstop = Thread. _thread__stop# Get Private Function def timelimited (timeout): def decorator (function): def decorator2 (*args,**kwargs): Class time Limited (Thread): def __init__ (self,_error= None,): thread.__init__ (self) self._error = _error def run (self): Try:self.result = function (*args,**kwargs) except 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 TIMEOUTEXCEP tion (' 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@timelimit Ed (2) def fn_1 (secs): TiMe.sleep (secs) return ' finished ' if __name__ = = "__main__": Print fn_1 (4)
Hopefully this article will help you with Python programming.