python限制函数的执行时间
import signal
class TimeoutException(Exception):
pass
def timeout_handler(signum, frame):
raise TimeoutException()
def limit_time(seconds=10):
def decorator(func):
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
except TimeoutException:
return None
finally:
signal.alarm(0)
return result
return wrapper
return decorator
运行
@limit_time(seconds=5)
def my_function():
# 在这里编写需要限制执行时间的代码
pass
result = my_function()