1. # pip install func_timeout
    2. from func_timeout import func_set_timeout
    3. from func_timeout.exceptions import FunctionTimedOut
    4. import time
    5. @func_set_timeout(5) # 函数执行多少秒后退出
    6. def task():
    7. index = 1
    8. while True:
    9. print('{} hello world!'.format(index))
    10. time.sleep(1)
    11. index += 1
    12. if __name__ == '__main__':
    13. try:
    14. task()
    15. except FunctionTimedOut as e:
    16. print("超时退出...", str(e))

    运行结果:

    1. 1 hello world!
    2. 2 hello world!
    3. 3 hello world!
    4. 4 hello world!
    5. 5 hello world!
    6. 6 hello world!
    7. 超时退出... Function task (args=()) (kwargs={}) timed out after 5.000000 seconds.