【发布时间】:2011-04-20 11:58:59
【问题描述】:
你怎么能有一个函数或东西在你的程序退出之前被执行?我有一个将在后台持续运行的脚本,我需要它在退出之前将一些数据保存到文件中。有这样做的标准方法吗?
【问题讨论】:
-
脚本不应该停止,但也许有人会终止进程或按 Ctrl+\ 或其他东西。
你怎么能有一个函数或东西在你的程序退出之前被执行?我有一个将在后台持续运行的脚本,我需要它在退出之前将一些数据保存到文件中。有这样做的标准方法吗?
【问题讨论】:
查看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.
如果您希望某些东西始终运行,即使出现错误,请像这样使用 try: finally: -
def main():
try:
execute_app()
finally:
handle_cleanup()
if __name__=='__main__':
main()
如果您还想处理异常,可以在 finally: 之前插入 except:
【讨论】:
如果您通过引发 KeyboardInterrupt(例如,通过按 Ctrl-C)来停止脚本,您可以将其作为标准异常捕获。同样的方法也可以抓到SystemExit。
try:
...
except KeyboardInterrupt:
# clean up
raise
我提这个只是为了让你知道;执行此操作的“正确”方法是上面提到的 atexit 模块。
【讨论】:
如果您有在程序的整个生命周期中存在的类对象,您还可以使用 __del__(self) 方法从类中执行命令:
class x:
def __init__(self):
while True:
print ("running")
sleep(1)
def __del__(self):
print("destructuring")
a = x()
如果执行被中止,这也适用于正常程序结束,肯定会有一些例外:
running
running
running
running
running
Traceback (most recent call last):
File "x.py", line 14, in <module>
a = x()
File "x.py", line 8, in __init__
sleep(1)
KeyboardInterrupt
destructuring
【讨论】: