How Python uses adorners and threads to limit function execution time _python

Source: Internet
Author: User

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.

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.