如何在终止时执行代码

时间:2018-08-03 10:49:08

标签: python exception-handling try-catch finally

我希望我的代码的一部分仅在手动停止程序时执行(例如按下pycharm中的停止按钮)。我以为最终的声明可以为我做。像这样:

try:
   do_sth()
finally:
   print("you stopped the program")

但是它不起作用。我最终都尝试了,除了都没有用。我以为,当我们停止程序运行时,发生了keyboard_intrrupt错误,因此终于可以正常工作了。

有什么主意吗?

1 个答案:

答案 0 :(得分:1)

您可以使用atexit库。

来自documentation

  

atexit模块定义了注册和注销清除功能的功能。这样注册的功能会在正常解释器终止后自动执行。

这可以像这样实现:

#Rest of program...

def before_termination():
    #Do something...

import atexit    
atexit.register(before_termination)

但是,只有在正常程序终止时才调用它,如果发生键盘中断则不会调用。