python - 如何在脚本退出时可靠地调用 Python 函数?

标签 python python-2.7

如何注册一个函数,其中包含所有正确的处理程序等,以便在 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/

相关文章:

python - 如何在不询问用户的情况下存储用户详细信息?

python - 找出 sqlalchemy orm 中的根引用

python - 在 Python 中将自定义格式的稀疏矩阵 X 与目标数组 Y 连接起来

python - 读取一个巨大的 .csv 文件

Python 显示进度

python - 从字符串创建子字符串列表

python - 如何在 MongoDB/Python/Django 中按名字和姓氏搜索用户

python - PEP 3103 : Difference between switch case and if statement code blocks

python - 随机森林修剪

python - 如何一次在 mongodb 中创建 100000 个条目?