首页 > 解决方案 > Python:检查程序是否正在关闭

问题描述

全部。

有没有办法使用 Python 检查当前正在运行的脚本是否被请求关闭?例如,如果我按下右上角的 X-Button(关闭程序按钮)来关闭它,或者以任何其他方式结束脚本,脚本可以在结束之前执行一些代码吗?例子:

# script goes here...

if Script_To_Be_Closed: # replace this with an actual line of code.
    do_stuff

标签: pythonpython-3.x

解决方案


您可以使用多个选项,例如捕获键盘中断,但最简单的是 atexit,它在脚本结束时执行一个函数(实际上除了硬进程终止)。

import atexit

def my_exit_function(some_argument):
    // Your exit code goes here
    print(some_argument)


if __name__ == '__main__':
    atexit.register(my_exit_function, 'some argument', )

    // Your script goes here

推荐阅读