如何在终止时执行代码

How to have code executed on termination

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

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

但它不起作用。我最后和除了 none 都试过了。我想当我们从 运行 停止程序时,发生了 keyboard_intrrupt 错误,所以最终一定成功了。

有什么想法吗?

您可以使用 atexit 库。

来自documentation

The atexit module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination.

可以这样实现:

#Rest of program...

def before_termination():
    #Do something...

import atexit    
atexit.register(before_termination)

然而,这只会在程序正常终止时调用,如果发生键盘中断则不会。