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

2024-05-01 22:02:17 发布

您现在位置:Python中文网/ 问答频道 /正文

当Python脚本退出(成功与否)时,如何使用所有正确的处理程序等来注册一个函数?在

我试过:

@atexit.register
def finalise():
    '''
    Function handles program close
    '''
    print("Tidying up...")
    ...
    print("Closing")

…但当用户关闭命令提示符窗口时,它不会被调用(因为@atexit.register修饰函数在exitcode为非零时不会被调用)

我正在寻找一种方法来保证在程序退出时调用finalise(),而不考虑错误。在

就上下文而言,我的Python程序是一个持续循环的服务程序,目的是一直运行。在

提前谢谢


Tags: 函数程序脚本register处理程序closedeffunction
3条回答

我认为用纯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

你试过在你的主函数或代码块中捕捉所有类型的异常吗?在

For context, my Python program is a continually looping service program that aims to run all the time.

这很难得到正确的结果(参见How do you create a daemon in Python?)。您应该使用http://pypi.python.org/pypi/python-daemon/这样的库。在

相关问题 更多 >