2

How do you register a function with all the correct handlers etc to be called when the Python script is exitted (successfully or not)?

I have tried:

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

...but this does not get called when the user closes the command prompt window for example (because @atexit.register decorated functions do not get called when the exitcode is non zero)

I am looking for a way of guaranteeing finalise() is called on program exit, regardless of errors.

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

Thanks in advance

4

5 回答 5

3

我不认为它可以在纯 Python 中完成。从文档

注意:当程序被 Python 未处理的信号杀死、检测到 Python 致命内部错误或调用 os._exit() 时,不会调用通过此模块注册的函数。

我认为您可能会发现这很有用:如何在 python 中捕获命令提示符窗口关闭事件

于 2012-12-18T11:30:35.640 回答
0

就上下文而言,我的 Python 程序是一个不断循环的服务程序,旨在始终运行。

这很难正确解决(请参阅如何在 Python 中创建守护程序?)。您应该改用http://pypi.python.org/pypi/python-daemon/之类的库。

于 2012-12-18T11:58:52.680 回答
0

您是否尝试在主函数或代码块中捕获各种异常?

于 2012-12-18T11:28:14.297 回答
0

这个应该工作

Ctrl-C断言失败时和断言失败时都有效。也许您可以使用类似的构造并将其打包为装饰器或其他任何东西。

def main():
  print raw_input('> ')
  # do all your stuff here  

if __name__ == '__main__':
  try:
    main()
  finally:
    print 'Bye!'
于 2012-12-18T11:37:19.300 回答
-1
atexit.register(func)

func = lambda x: x

使用http://docs.python.org/2/library/atexit.html

于 2012-12-18T11:42:39.540 回答