Timeout on a function call

后端 未结 18 1903
挽巷
挽巷 2020-11-21 04:53

I\'m calling a function in Python which I know may stall and force me to restart the script.

How do I call the function or what do I wrap it in so that if it takes

18条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 05:05

    Building on and and enhancing the answer by @piro , you can build a contextmanager. This allows for very readable code which will disable the alaram signal after a successful run (sets signal.alarm(0))

    @contextmanager
    def timeout(duration):
        def timeout_handler(signum, frame):
            raise Exception(f'block timedout after {duration} seconds')
        signal.signal(signal.SIGALRM, timeout_handler)
        signal.alarm(duration)
        yield
        signal.alarm(0)
    
    def sleeper(duration):
        time.sleep(duration)
        print('finished')
    

    Example usage:

    In [19]: with timeout(2):
        ...:     sleeper(1)
        ...:     
    finished
    
    In [20]: with timeout(2):
        ...:     sleeper(3)
        ...:         
    ---------------------------------------------------------------------------
    Exception                                 Traceback (most recent call last)
     in ()
          1 with timeout(2):
    ----> 2     sleeper(3)
          3 
    
     in sleeper(t)
          1 def sleeper(t):
    ----> 2     time.sleep(t)
          3     print('finished')
          4 
    
     in timeout_handler(signum, frame)
          2 def timeout(duration):
          3     def timeout_handler(signum, frame):
    ----> 4         raise Exception(f'block timedout after {duration} seconds')
          5     signal.signal(signal.SIGALRM, timeout_handler)
          6     signal.alarm(duration)
    
    Exception: block timedout after 2 seconds
    

提交回复
热议问题