# pip install func_timeoutfrom func_timeout import func_set_timeoutfrom func_timeout.exceptions import FunctionTimedOutimport time@func_set_timeout(5) # 函数执行多少秒后退出def task():index = 1while True:print('{} hello world!'.format(index))time.sleep(1)index += 1if __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.
