# pip install func_timeout
from func_timeout import func_set_timeout
from func_timeout.exceptions import FunctionTimedOut
import time
@func_set_timeout(5) # 函数执行多少秒后退出
def task():
index = 1
while True:
print('{} hello world!'.format(index))
time.sleep(1)
index += 1
if __name__ == '__main__':
try:
task()
except FunctionTimedOut as e:
print("超时退出...", str(e))
运行结果:
1 hello world!
2 hello world!
3 hello world!
4 hello world!
5 hello world!
6 hello world!
超时退出... Function task (args=()) (kwargs={}) timed out after 5.000000 seconds.