Python uses adorners and threads to limit the way a function executes time

Source: Internet
Author: User
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.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.