zoukankan      html  css  js  c++  java
  • 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.

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

  • 相关阅读:
    高可用keepalived的抢占式与非抢占式
    keepalived搭建
    高可用概念
    Nginx优雅显示错误页面
    Nginx调整上传文件大小
    nginx的root和alias区别
    nginx的include
    每日总结2.18
    每日总结2.17
    每日总结2.16
  • 原文地址:https://www.cnblogs.com/Frange/p/9371072.html
Copyright © 2011-2022 走看看