如何注册一个函数,其中包含所有正确的处理程序等,以便在 Python 脚本退出(成功或失败)时调用?
我已经尝试过:
@atexit.register
def finalise():
'''
Function handles program close
'''
print("Tidying up...")
...
print("Closing")
...但是,例如,当用户关闭命令提示符窗口时,不会调用此函数(因为当退出代码非零时,不会调用 @atexit.register
修饰函数)
我正在寻找一种方法来保证在程序退出时调用finalise()
,而不管错误如何。
就上下文而言,我的 Python 程序是一个不断循环的服务程序,旨在始终运行。
提前致谢
最佳答案
我不认为它可以用纯Python来完成。来自 documentation :
Note: the functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called.
我想您可能会发现这很有用:How to capture a command prompt window close event in python
关于python - 如何在脚本退出时可靠地调用 Python 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13931887/