Fork me on GitHub

[python]注册Shutdown函数

有个模块叫atexit,它可以让你在脚本运行完后立马执行一些代码。

假如你想在脚本执行结束时测量一些基准数据,比如运行了多长时间:

import atexit
import time
import math
 
def microtime(get_as_float = False) :
    if get_as_float:
        return time.time()
    else:
        return '%f %d' % math.modf(time.time())
start_time = microtime(False)
atexit.register(start_time)
 
def shutdown():
    global start_time
    print "Execution took: {0} seconds".format(start_time)
 
atexit.register(shutdown)
 
# Execution took: 0.297000 1387135607 seconds
# Error in atexit._run_exitfuncs:
# Traceback (most recent call last):
#   File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
#     func(*targs, **kargs)
# TypeError: 'str' object is not callable
# Error in sys.exitfunc:
# Traceback (most recent call last):
#   File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
#     func(*targs, **kargs)
# TypeError: 'str' object is not callable

  

打眼看来很简单。只需要将代码添加到脚本的最底层,它将在脚本结束前运行。但如果脚本中有一个致命错误或者脚本被用户终止,它可能就不运行了。

当你使用atexit.register()时,你的代码都将执行,不论脚本因为什么原因停止运行。

posted @ 2017-07-25 21:11  [sigai]  阅读(393)  评论(0编辑  收藏  举报