在程序退出前做些事情 [英] Doing something before program exit
问题描述
你怎么能有一个函数或者什么东西会在程序退出之前执行?我有一个将在后台不断运行的脚本,我需要它在退出之前将一些数据保存到文件中。有没有这样做的标准方法?
> module:http:// docs .python.org / library / atexit.html
例如,如果我想在应用程序终止时打印消息:
import atexit
def exit_handler():
print'My application is ending!'
atexit.register(exit_handler)
请注意,这对于正常终止该脚本,但它不会在所有情况下被调用(例如致命的内部错误)。
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?
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).
这篇关于在程序退出前做些事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!