End python code after 60 seconds

后端 未结 5 1345
甜味超标
甜味超标 2021-01-15 04:14

Below there is some fully functioning code.

I am planning to execute this code through command line, however I would like it to end after 60 seconds.

Does an

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-15 04:25

    This is my favorite way of doing timeout.

    def timeout(func, args=None, kwargs=None, TIMEOUT=10, default=None, err=.05):
        if args is None:
            args = []
        elif hasattr(args, "__iter__") and not isinstance(args, basestring):
            args = args
        else:
            args = [args]
    
        kwargs = {} if kwargs is None else kwargs
    
        import threading
        class InterruptableThread(threading.Thread):
            def __init__(self):
                threading.Thread.__init__(self)
                self.result = None
    
            def run(self):
                try:
                    self.result = func(*args, **kwargs)
                except:
                    self.result = default
    
        it = InterruptableThread()
        it.start()
        it.join(TIMEOUT* (1 + err))
        if it.isAlive():
            return default
        else:
            return it.result
    

提交回复
热议问题