Created
November 13, 2013 13:28
-
-
Save HugoPresents/7449101 to your computer and use it in GitHub Desktop.
limit execution time of a function call in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it's only the permission to run in the main process,