right way to run some code with timeout in Python

后端 未结 9 1744
余生分开走
余生分开走 2020-12-13 18:18

I looked online and found some SO discussing and ActiveState recipes for running some code with a timeout. It looks there are some common approaches:

  • Use threa
9条回答
  •  情深已故
    2020-12-13 19:07

    solving with the 'with' construct and merging solution from -

    • Timeout function if it takes too long to finish
    • this thread which work better.

      import threading, time
      
      class Exception_TIMEOUT(Exception):
          pass
      
      class linwintimeout:
      
          def __init__(self, f, seconds=1.0, error_message='Timeout'):
              self.seconds = seconds
              self.thread = threading.Thread(target=f)
              self.thread.daemon = True
              self.error_message = error_message
      
          def handle_timeout(self):
              raise Exception_TIMEOUT(self.error_message)
      
          def __enter__(self):
              try:
                  self.thread.start()
                  self.thread.join(self.seconds)
              except Exception, te:
                  raise te
      
          def __exit__(self, type, value, traceback):
              if self.thread.is_alive():
                  return self.handle_timeout()
      
      def function():
          while True:
              print "keep printing ...", time.sleep(1)
      
      try:
          with linwintimeout(function, seconds=5.0, error_message='exceeded timeout of %s seconds' % 5.0):
              pass
      except Exception_TIMEOUT, e:
          print "  attention !! execeeded timeout, giving up ... %s " % e
      

提交回复
热议问题