【问题标题】:How to have code executed on termination如何在终止时执行代码
【发布时间】:2019-01-11 06:00:47
【问题描述】:

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

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

但它不起作用。我最后和除了都试过了,但都没有奏效。我想当我们停止程序运行时,发生了keyboard_intrrupt 错误,所以最终肯定可以工作。

有什么想法吗?

【问题讨论】:

    标签: python exception-handling try-catch finally


    【解决方案1】:

    您可以使用atexit 库。

    来自documentation

    atexit 模块定义了注册和注销清理函数的函数。这样注册的函数会在解释器正常终止时自动执行。

    这可以这样实现:

    #Rest of program...
    
    def before_termination():
        #Do something...
    
    import atexit    
    atexit.register(before_termination)
    

    但是,这仅在正常程序终止期间调用,而不是在发生键盘中断时调用。

    【讨论】:

    • 当我使用它时,我不需要在我的代码中的某处调用该函数吗?
    • 非常感谢
    • @aref 可能应该提到atexit 仅在正常程序终止期间调用,而不是在您在 pycharm 中的键盘中断/停止时调用。
    • @dheiberg 谢谢,我已将其添加到答案中:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 2017-04-06
    • 1970-01-01
    • 2011-05-27
    相关资源
    最近更新 更多