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()
标签:return,函数,python,signal,seconds,TimeoutException,result,限制,def
From: https://www.cnblogs.com/c-x-a/p/17623051.html