在程序退出前做某事 [英] Doing something before program exit

查看:34
本文介绍了在程序退出前做某事的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么能有一个函数或一些东西在你的程序退出之前会被执行?我有一个脚本将在后台不断运行,我需要它在退出之前将一些数据保存到文件中.有没有标准的方法来做到这一点?

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?

推荐答案

查看 atexit 模块:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆