Timeout on a function call

后端 未结 18 1371
挽巷
挽巷 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 04:59

    Here is a slight improvement to the given thread-based solution.

    The code below supports exceptions:

    def runFunctionCatchExceptions(func, *args, **kwargs):
        try:
            result = func(*args, **kwargs)
        except Exception, message:
            return ["exception", message]
    
        return ["RESULT", result]
    
    
    def runFunctionWithTimeout(func, args=(), kwargs={}, timeout_duration=10, default=None):
        import threading
        class InterruptableThread(threading.Thread):
            def __init__(self):
                threading.Thread.__init__(self)
                self.result = default
            def run(self):
                self.result = runFunctionCatchExceptions(func, *args, **kwargs)
        it = InterruptableThread()
        it.start()
        it.join(timeout_duration)
        if it.isAlive():
            return default
    
        if it.result[0] == "exception":
            raise it.result[1]
    
        return it.result[1]
    

    Invoking it with a 5 second timeout:

    result = timeout(remote_calculate, (myarg,), timeout_duration=5)
    

提交回复
热议问题