atexit --- 退出處理函式


The atexit module defines functions to register and unregister exit handlers: functions that are automatically executed "at exit", that is, upon normal program termination (for instance, if sys.exit() is called or the main module's execution completes) or, more generally, upon interpreter shutdown.

在退出時,所有已註冊的退出處理函式會依照註冊的相反順序被呼叫。如果你依序註冊了 A、B 和 C,在直譯器關閉時,它們會以 C、B、A 的順序執行。這邊做的假設是較低階的模組通常會在較高階模組之前被引入,因此較低階模組必須在比較後面才被清理。

如果在執行退出處理函式期間引發例外,則會列印回溯 (traceback)(除非引發 SystemExit)並儲存例外資訊。在所有退出處理函式都有嘗試運作過後,將重新引發最後一個引發的例外。

In programs that use multiple interpreters, each interpreter has its own stack of exit handlers, which are executed when the interpreter shuts down (for example, with concurrent.interpreters.Interpreter.close() or the C API Py_EndInterpreter()). Registration functions in this module only affect the interpreter they are called from.

注意:當程式被一個 Python 未處理的訊號終止、偵測到 Python 發生嚴重內部錯誤,或者 os._exit() 被呼叫時,退出處理函式就不會被呼叫。

注意:在清理函式中註冊或註銷函式的作用並未定義。

警告

When writing exit handlers, especially in C API extensions, keep in mind that other exit handlers may still run arbitrary Python code after you clean up. Such code should succeed or fail with an exception, rather than crash.

在 3.12 版的變更: 在退出處理函式中嘗試啟動新執行緒或以 os.fork() 建立新行程,現在會導致 RuntimeError。在此之前,這可能會在 Python 主 runtime 執行緒釋放執行緒狀態、而內部 threading 例程或新行程又嘗試使用該狀態時產生競態條件 (race condition),進而導致崩潰 (crash) 而非正常關閉。

在 3.7 版的變更: 當與子直譯器 (subinterpreter) 一起使用時,已註冊函式對於它們所註冊的直譯器來說是區域的 (local)。

atexit.register(func, *args, **kwargs)

將 func 註冊為退出處理函式。任何要傳遞給 func 的可選引數都必須作為引數傳遞給 register()。可以多次註冊相同的函式和引數。

該函式回傳 func,這使得可以將其作為裝飾器使用。

atexit.unregister(func)

從退出處理函式串列中移除 func。如果 func 先前未被註冊,則 unregister() 不會執行任何操作。如果 func 已被註冊多次,則該函式在 atexit 呼叫堆疊 (call stack) 中的所有存在都會被刪除。會在註銷期間於內部使用相等性比較 (==),因此函式參照不需要具有匹配的識別性。

也參考

readline 模組

atexit 用於讀取和寫入 readline 歷史檔案的一個不錯的範例。

atexit 範例

以下的簡單範例示範了模組如何在被引入時以檔案來初始化計數器,並在程式終止時自動儲存計數器的更新值,而不需要仰賴應用程式在終止時明確呼叫該模組。

try:
    with open('counterfile') as infile:
        _count = int(infile.read())
except FileNotFoundError:
    _count = 0

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

def savecounter():
    with open('counterfile', 'w') as outfile:
        outfile.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')
# 或是:
atexit.register(goodbye, adjective='nice', name='Donny')

作為裝飾器使用:

import atexit

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

這只適用於可以不帶引數呼叫的函式。