python限制函数执行时间

时间:2021-10-29 18:11:37
from:https://*.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python
当有些函数执行时间过长,影响整个程序运行时,可以使用此方法进行限制,超时会报错。
from __future__ import with_statement # Required in 2.5
import signal
from contextlib import contextmanager

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(
10):
long_function_call()
except TimeoutException, msg:
print "Timed out!"