views:

322

answers:

1

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

+2  A: 
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/

Mike Leffard
I'd want to modify that to be usable as a decorator.
Dustin