Skip to content

Instantly share code, notes, and snippets.

@luispedro
Created March 23, 2010 22:40
Show Gist options
  • Save luispedro/341777 to your computer and use it in GitHub Desktop.
Save luispedro/341777 to your computer and use it in GitHub Desktop.
set operation timers in python
from __future__ import division, with_statement
import signal
__all__ = ['TimeOutError', 'timeout']
class TimeOutError(Exception):
def __init__(self):
Exception.__init__(self,'Timeout')
def _raise_TimeOut(sig, stack):
raise TimeOutError()
class timeout(object):
def __init__(self, timeout, raise_exception=True):
self.timeout = timeout
self.raise_exception = raise_exception
def __enter__(self):
self.old_handler = signal.signal(signal.SIGALRM, _raise_TimeOut)
signal.alarm(self.timeout)
def __exit__(self, exc_type, exc_val, exc_tb):
signal.signal(signal.SIGALRM, self.old_handler)
signal.alarm(0)
if exc_type is not TimeOutError:
return False # Never swallow other exceptions
return not self.raise_exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment