Python atexit模块

Posted frange

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python atexit模块相关的知识,希望对你有一定的参考价值。

atexit模块介绍

作用:让注册的函数在解释器正常终止时自动执行,可以注册多个函数,所注册的函数会逆序执行(据查资料,造成逆序的原因为函数压栈造成的,先进后出)

1、正常注册 ,示例如下。

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

def hello():
    print(hello world!)

def a():
    print(a)

import atexit
atexit.register(goodbye, Donny, nice)
atexit.register(a)
hello()
# 输出
PS E:Atomfilesapp> python .ex9_atexit.py
hello world!
a
Goodbye Donny, it was nice to meet you.

2、可以使用装饰器来注册,但是只适用于没有参数时调用。

import atexit

@atexit.register
def hello():
    print(Hello world!)

# 输出
PS E:Atomfilesapp> python .ex9_atexit.py
Hello world!

3、取消注册, 示例如下。

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

def hello():
    print(hello world!)

def a():
    print(a)

import atexit
atexit.register(goodbye, Donny, nice)
atexit.register(a)
atexit.register(a)
atexit.register(a)
hello()
atexit.unregister(a)
# 输出
PS E:Atomfilesapp> python .ex9_atexit.py
hello world!
Goodbye Donny, it was nice to meet you.

这个模块一般用来在程序结束时,做资源清理。

 

以上是关于Python atexit模块的主要内容,如果未能解决你的问题,请参考以下文章

Atexit没有在python中注册

常用python日期日志获取内容循环的代码片段

是否可以更改使用 atexit() 注册的函数中的退出代码?

是否有用 C 编写的 python 模块的 fini 例程?

实时/非批处理应用程序中的 C 退出代码和 atexit()

Python - 模块