2

Does anyone know a good solution for implementing a function similar to Ruby's timeout in Python? I've googled it and didn't really see anything very good. Thanks for the help.

Here's a link to the Ruby documentation http://www.ruby-doc.org/stdlib/libdoc/timeout/rdoc/index.html

Nope
  • 34,682
  • 42
  • 94
  • 119
  • See http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python – tzot Dec 15 '08 at 09:26

1 Answers1

2
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
    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_duration)
    if it.isAlive():
        return default
    else:
        return it.result

from:

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

John T
  • 23,735
  • 11
  • 56
  • 82