程序退出前做些事情

问题:程序退出前做些事情

在程序退出之前,如何拥有要执行的功能或某些东西?我有一个脚本会在后台不断运行,并且我需要它在退出之前将一些数据保存到文件中。有这样做的标准方法吗?

How can you have a function or something that will be executed before your program quits? I have a script that will be constantly running in the background, and I need it to save some data to a file before it exits. Is there a standard way of doing this?


回答 0

检出atexit模块:

http://docs.python.org/library/atexit.html

例如,如果我想在应用程序终止时打印一条消息:

import atexit

def exit_handler():
    print 'My application is ending!'

atexit.register(exit_handler)

请注意,这对于正常终止脚本非常有用,但是在所有情况下都不会调用它(例如致命的内部错误)。

Check out the atexit module:

http://docs.python.org/library/atexit.html

For example, if I wanted to print a message when my application was terminating:

import atexit

def exit_handler():
    print 'My application is ending!'

atexit.register(exit_handler)

Just be aware that this works great for normal termination of the script, but it won’t get called in all cases (e.g. fatal internal errors).


回答 1

如果您希望某些东西始终运行,即使出现错误,也可以try: finally:这样使用-

def main():
    try:
        execute_app()
    finally:
        handle_cleanup()

if __name__=='__main__':
    main()

如果您还想处理异常,可以在except:之前插入finally:

If you want something to always run, even on errors, use try: finally: like this –

def main():
    try:
        execute_app()
    finally:
        handle_cleanup()

if __name__=='__main__':
    main()

If you want to also handle exceptions you can insert an except: before the finally:


回答 2

如果通过引发KeyboardInterrupt(例如,按Ctrl-C)停止脚本,则可以将其作为标准异常捕获。您也可以SystemExit用相同的方式捕捉。

try:
    ...
except KeyboardInterrupt:
    # clean up
    raise

我提到这一点只是为了让您知道。做到这一点的“正确”方法是上述atexit模块。

If you stop the script by raising a KeyboardInterrupt (e.g. by pressing Ctrl-C), you can catch that just as a standard exception. You can also catch SystemExit in the same way.

try:
    ...
except KeyboardInterrupt:
    # clean up
    raise

I mention this just so that you know about it; the ‘right’ way to do this is the atexit module mentioned above.