How to limit execution time of a function call in Python

后端 未结 10 1882
遥遥无期
遥遥无期 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 10:56

    Here's a timeout function I think I found via google and it works for me.

    From: http://code.activestate.com/recipes/473878/

    def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
        '''This function will spwan a thread and run the given function using the args, kwargs and 
        return the given default value if the timeout_duration is exceeded 
        ''' 
        import threading
        class InterruptableThread(threading.Thread):
            def __init__(self):
                threading.Thread.__init__(self)
                self.result = default
            def run(self):
                try:
                    self.result = func(*args, **kwargs)
                except:
                    self.result = default
        it = InterruptableThread()
        it.start()
        it.join(timeout_duration)
        if it.isAlive():
            return it.result
        else:
            return it.result   
    

提交回复
热议问题