Python进阶之atexit模块使用

 

 

微信搜索“菜鸟童靴”,选择“关注公众号”

我们一起开启Python进阶之旅!

 

如何让Python在退出时强制运行一段代码,说起这个需求,我们就不得不说Python atexit模块了:

退出处理器 atexit 模块定义了清理函数的注册和反注册函数. 被注册的函数会在解释器正常终止时执行. atexit 会按照注册顺序的逆序执行; 如果你注册了 A, BC, 那么在解释器终止时会依序执行 C, B, A.

看完这段介绍,有点类似栈的原理,后进先出

 

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, 'Mr.Yang', 'nice')#3
atexit.register(a)#2
hello()#1正常程序首先被执行

#执行顺序 1 2 3

运行结果

 

 

2、 作为 [decorator]: 使用,使用场景, 但是只适用于没有参数时调用

举例说明,对上述代码稍作修改:

import atexit

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

hello()

#运行结果
#hello world!
#a

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, 'Mr.Yang', 'nice')#3
atexit.register(a)#2
hello()#1正常程序首先被执行
atexit.unregister(a)
#正常执行顺序 1 2 3

#由于设置了取消注册atexit.unregister(a),

#注销后执行顺序 1 3

运行结果:

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

应用场景一:

既能让程序报错,又能在报错已经还能运行clean()呢?

import atexit

@atexit.register
def clean():
   print('清理环境相关的代码')

def test():
   example = {"a": 1, "b": 2}
   print(example["c"])#程序报错
test()

运行结果:

 

 

这样一来,我们不需要显式调用clean函数了。无论程序正常结束,还是程序异常报错,clean函数里面的内容总会执行。

文章首发于微信公众号菜鸟童靴,不定期更新,如有需要后台加微信

 

官方文档:https://docs.python.org/zh-cn/3.7/library/atexit.html

参考链接:https://mp.weixin.qq.com/s/lNwSBhcp9ktwgaGWpXNq-A

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值