擅长:python、mysql、java
<p>您可以对<code>atexit</code>模块进行修补-如下所示:</p>
<pre><code>import atexit
from queue import LifoQueue
save_register = atexit.register
atexit_queue = LifoQueue()
def my_register(func, *args, **kwargs):
save_register(func, *args, **kwargs)
atexit_queue.put((func, args, kwargs))
atexit.register = my_register
if __name__ == '__main__':
def func1():
print('func1() called')
def func2(arg):
print(f'func2({arg}) called')
def func3(arg, kwarg1=1, kwarg2='foo'):
print(f'func3({arg}, kwarg1={kwarg1}, kwarg2={kwarg2!r}) called')
atexit.register(func1)
atexit.register(func2, 1)
atexit.register(func3, 2, kwarg1=42, kwarg2='bar')
print('Calling queued atexit functions:\n')
while atexit_queue.qsize():
func, args, kwargs = atexit_queue.get()
atexit.unregister(func) # Prevent it from being called again.
func(*args, **kwargs)
</code></pre>
<p>输出:</p>
<pre class="lang-none prettyprint-override"><code>Calling queued atexit functions:
func3(2, kwarg1=42, kwarg2='bar') called
func2(1) called
func1() called
</code></pre>