Python uses decorator and thread to limit function execution time

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

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: 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.