Answers:
检出atexit
模块:
http://docs.python.org/library/atexit.html
例如,如果我想在应用程序终止时打印一条消息:
import atexit
def exit_handler():
print 'My application is ending!'
atexit.register(exit_handler)
请注意,这对于正常终止脚本非常有用,但是在所有情况下都不会调用它(例如致命的内部错误)。
Note The exit function is not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called
。