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.

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

  • 相关阅读:
    hdu 4947
    hdu 4946
    hdu 4944
    hdu 4942
    hdu 4941
    PAT 【L2-011 玩转二叉树】
    PAT【L2-006 树的遍历】
    XYNUOJ 【2070: 重建二叉树】
    XYNUOJ 【1367: 二叉链表存储的二叉树】
    XYNUOJ 2390【二叉树遍历2】
  • 原文地址:https://www.cnblogs.com/Frange/p/9371072.html
Copyright © 2011-2022 走看看