break the function after certain time

后端 未结 5 1860
长情又很酷
长情又很酷 2020-11-27 16:34

In python, for a toy example:

for x in range(0, 3):
    # call function A(x)

I want to continue the for loop if function A takes more than

5条回答
  •  甜味超标
    2020-11-27 16:58

    I think creating a new process may be overkill. If you're on Mac or a Unix-based system, you should be able to use signal.SIGALRM to forcibly time out functions that take too long. This will work on functions that are idling for network or other issues that you absolutely can't handle by modifying your function. I have an example of using it in this answer:

    https://stackoverflow.com/a/24921763/3803152

    Editing my answer in here, though I'm not sure I'm supposed to do that:

    import signal
    
    class TimeoutException(Exception):   # Custom exception class
        pass
    
    def timeout_handler(signum, frame):   # Custom signal handler
        raise TimeoutException
    
    # Change the behavior of SIGALRM
    signal.signal(signal.SIGALRM, timeout_handler)
    
    for i in range(3):
        # Start the timer. Once 5 seconds are over, a SIGALRM signal is sent.
        signal.alarm(5)    
        # This try/except loop ensures that 
        #   you'll catch TimeoutException when it's sent.
        try:
            A(i) # Whatever your function that might hang
        except TimeoutException:
            continue # continue the for loop if function A takes more than 5 second
        else:
            # Reset the alarm
            signal.alarm(0)
    

    This basically sets a timer for 5 seconds, then tries to execute your code. If it fails to complete before time runs out, a SIGALRM is sent, which we catch and turn into a TimeoutException. That forces you to the except block, where your program can continue.

    EDIT: whoops, TimeoutException is a class, not a function. Thanks, abarnert!

提交回复
热议问题