This document is for an old version of Python that is no longer supported. You should upgrade and read the Python 当前稳定版本的文档.

# 28.9. `atexit` — 退出处理器

2.0 新版功能.

Source code: Lib/atexit.py

The `atexit` module defines a single function to register cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. `atexit` runs these functions in the reverse order in which they were registered; if you register `A`, `B`, and `C`, at interpreter termination time they will be run in the order `C`, `B`, `A`.

注意: 通过该模块注册的函数, 在程序被未被 Python 捕获的信号杀死时并不会执行, 在检测到 Python 内部致命错误以及调用了 `os._exit()` 时也不会执行.

This is an alternate interface to the functionality provided by the `sys.exitfunc()` variable.

Note: This module is unlikely to work correctly when used with other code that sets `sys.exitfunc`. In particular, other core Python modules are free to use `atexit` without the programmer’s knowledge. Authors who use `sys.exitfunc` should convert their code to use `atexit` instead. The simplest way to convert code that sets `sys.exitfunc` is to import `atexit` and register the function that had been bound to `sys.exitfunc`.

`atexit.``register`(func[, *args[, **kwargs]])

  将 func 注册为终止时执行的函数. 任何传给 func 的可选的参数都应当作为参数传给 `register()`. 可以多次注册同样的函数及参数.

  在正常的程序终止时 (举例来说, 当调用了 `sys.exit()` 或是主模块的执行完成时), 所有注册过的函数都会以后进先出的顺序执行. 这样做是假定更底层的模块通常会比高层模块更早引入, 因此需要更晚清理.

  如果在 exit 处理程序执行期间引发了异常，将会打印回溯信息 (除非引发的是 `SystemExit`) 并且异常信息会被保存。 在所有 exit 处理程序获得运行机会之后，所引发的最后一个异常会被重新引发。

  在 2.6 版更改: This function now returns func, which makes it possible to use it as a decorator.

参见

模块 `readline`

  使用 `atexit` 读写 `readline` 历史文件的有用的例子。

## 28.9.1. `atexit` 示例

以下简单例子演示了一个模块在被导入时如何从文件初始化一个计数器，并在程序终结时自动保存计数器的更新值，此操作不依赖于应用在终结时对此模块进行显式调用。:

    try:
        _count = int(open("counter").read())
    except IOError:
        _count = 0

    def incrcounter(n):
        global _count
        _count = _count + n

    def savecounter():
        open("counter", "w").write("%d" % _count)

    import atexit
    atexit.register(savecounter)

位置和关键字参数也可传入 `register()` 以便传递给被调用的已注册函数:

    def goodbye(name, adjective):
        print 'Goodbye, %s, it was %s to meet you.' % (name, adjective)

    import atexit
    atexit.register(goodbye, 'Donny', 'nice')

    # or:
    atexit.register(goodbye, adjective='nice', name='Donny')

作为 decorator: 使用:

    import atexit

    @atexit.register
    def goodbye():
        print "You are now leaving the Python sector."

只有在函数不需要任何参数调用时才能工作.