Python atexit模块
生活随笔
收集整理的這篇文章主要介紹了
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:\Atom\files\app> python .\ex9_atexit.py hello world! a Goodbye Donny, it was nice to meet you.2、可以使用裝飾器來注冊,但是只適用于沒有參數時調用。
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import atexit@atexit.register def hello():print('Hello world!')# 輸出 PS E:\Atom\files\app> 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:\Atom\files\app> python .\ex9_atexit.py hello world! Goodbye Donny, it was nice to meet you.這個模塊一般用來在程序結束時,做資源清理。
總結
以上是生活随笔為你收集整理的Python atexit模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 爬虫使用固定代理IP
- 下一篇: python xlsxwriter使用方