Python 在程序退出前做某事
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3850261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Doing something before program exit
提问by RacecaR
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?
你怎么能有一个函数或某些东西在你的程序退出之前会被执行?我有一个将在后台不断运行的脚本,我需要它在退出之前将一些数据保存到文件中。有没有标准的方法来做到这一点?
采纳答案by Brent Writes Code
Check out the atexitmodule:
查看atexit模块:
http://docs.python.org/library/atexit.html
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).
请注意,这对于脚本的正常终止非常有用,但不会在所有情况下都被调用(例如致命的内部错误)。
回答by Katriel
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 SystemExitin the same way.
如果您通过引发 a KeyboardInterrupt(例如通过按 Ctrl-C)来停止脚本,您可以将其作为标准异常捕获。你也可以SystemExit用同样的方法捕捉。
try:
...
except KeyboardInterrupt:
# clean up
raise
I mention this just so that you know about it; the 'right' way to do this is the atexitmodule mentioned above.
我提到这一点只是为了让你了解它;做到这一点的“正确”方法是atexit上面提到的模块。
回答by Brian C. Lane
If you want something to always run, even on errors, use try: finally:like this -
如果您希望某些东西始终运行,即使出现错误,也可以try: finally:这样使用-
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:
如果您还想处理异常,您可以except:在finally:

