From 60f04f0a41971c11d86692471855b638181b511a Mon Sep 17 00:00:00 2001 From: Miroslav Stampar Date: Tue, 6 Apr 2010 14:33:57 +0000 Subject: [PATCH] new module for interruptable threads --- lib/utils/timeout.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 lib/utils/timeout.py diff --git a/lib/utils/timeout.py b/lib/utils/timeout.py new file mode 100644 index 000000000..f4db06ffb --- /dev/null +++ b/lib/utils/timeout.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import threading + +def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None): + 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 + + thread = InterruptableThread() + thread.start() + thread.join(timeout_duration) + if thread.isAlive(): + return default + else: + return thread.result