Python程序结束前处理

使用内置库 atexit 注册程序退出前要执行的函数.
程序崩溃和外部中断都会执行。

import atexit
import time


def f():
    print('结束')


atexit.register(f)

if __name__ == '__main__':
    for i in range(15):
        if i == 10:
            1/0
        time.sleep(1)
        print(i)

结果如下

conda activate base
(base) PC:~/Code/PyCode/test$ python test_finish.py
0
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
  File "/home/xxx/Code/PyCode/test/test_finish.py", line 14, in <module>
    1/0
ZeroDivisionError: division by zero
结束
(base) PC:~/Code/PyCode/test$ python test_finish.py
0
1
2
^CTraceback (most recent call last):
  File "/home/xxx/Code/PyCode/test/test_finish.py", line 15, in <module>
    time.sleep(1)
KeyboardInterrupt
结束
posted @ 2022-10-18 15:04  道友请留步W  阅读(200)  评论(0编辑  收藏  举报