首页 > 编程语言 >Python程序结束前处理

Python程序结束前处理

时间:2022-10-18 15:11:50浏览次数:44  
标签:__ finish Python py 程序 PyCode 处理 Code test

使用内置库 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
结束

标签:__,finish,Python,py,程序,PyCode,处理,Code,test
From: https://www.cnblogs.com/MasonHu/p/16802618.html

相关文章