How to limit execution time of a function call in Python

后端 未结 10 1927
遥遥无期
遥遥无期 2020-11-22 10:25

There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which

10条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 11:04

    An improvement on @rik.the.vik's answer would be to use the with statement to give the timeout function some syntactic sugar:

    import signal
    from contextlib import contextmanager
    
    class TimeoutException(Exception): pass
    
    @contextmanager
    def time_limit(seconds):
        def signal_handler(signum, frame):
            raise TimeoutException("Timed out!")
        signal.signal(signal.SIGALRM, signal_handler)
        signal.alarm(seconds)
        try:
            yield
        finally:
            signal.alarm(0)
    
    
    try:
        with time_limit(10):
            long_function_call()
    except TimeoutException as e:
        print("Timed out!")
    

提交回复
热议问题