| 1 |
atexit_callbacks = [] |
| 2 |
|
| 3 |
def register(func, *args, **kwargs): |
| 4 |
"""Register a function to be executed upon normal program termination. |
| 5 |
|
| 6 |
func - function to be called at exit |
| 7 |
args - optional arguments to pass to func |
| 8 |
kwargs - optional keyword arguments to pass to func |
| 9 |
|
| 10 |
func is returned to facilitate usage as a decorator.""" |
| 11 |
|
| 12 |
if not callable(func): |
| 13 |
raise TypeError("func must be callable") |
| 14 |
|
| 15 |
atexit_callbacks.append((func, args, kwargs)) |
| 16 |
return func |
| 17 |
|
| 18 |
def run_exitfuncs(): |
| 19 |
"Run all registered exit functions." |
| 20 |
|
| 21 |
for (func, args, kwargs) in reversed(atexit_callbacks): |
| 22 |
if func is None: |
| 23 |
|
| 24 |
continue |
| 25 |
try: |
| 26 |
func(*args, **kwargs) |
| 27 |
except BaseException as e: |
| 28 |
import __pypy__ |
| 29 |
__pypy__.write_unraisable("in atexit callback", e, func) |
| 30 |
|
| 31 |
clear() |
| 32 |
|
| 33 |
def clear(): |
| 34 |
"Clear the list of previously registered exit functions." |
| 35 |
del atexit_callbacks[:] |
| 36 |
|
| 37 |
def unregister(func): |
| 38 |
"""Unregister a exit function which was previously registered using |
| 39 |
atexit.register""" |
| 40 |
for i, (f, _, _) in enumerate(atexit_callbacks): |
| 41 |
if f == func: |
| 42 |
atexit_callbacks[i] = (None, None, None) |
| 43 |
|
| 44 |
def ncallbacks(): |
| 45 |
return len(atexit_callbacks) |