Skip to content

Instantly share code, notes, and snippets.

@HugoPresents
Created November 13, 2013 13:28
Show Gist options
  • Save HugoPresents/7449101 to your computer and use it in GitHub Desktop.
Save HugoPresents/7449101 to your computer and use it in GitHub Desktop.
limit execution time of a function call in Python
from __future__ import with_statement
import signal, time
from contextlib import contextmanager
def long_function_call():
while True:
if time.time() % 1 == 0:
print '*'
class TimeoutException(Exception): pass
@contextmanager
def time_limit(seconds):
def signal_handler(signum, frame):
raise TimeoutException, "Timed out!"
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
try:
with time_limit(3):
long_function_call()
except TimeoutException, msg:
print msg
@LeonardoRick
Copy link

it do not work on windows

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment