python 监听键盘事件,调用指定函数,以及在程序退出时调用函数处理退出后得事情

import datetime
import sys
import time


def func(mail):
    print('参数:{0}'.format(mail))
    print('时间:{0}'.format(datetime.datetime.now()))
    print('-' * 30)


def on_exit(a,b):
    global running
    print(f'退出程序{a},{b}')
    running = False
    sys.exit()

def on_exitee():
    print("程序停止时执行的钩子函数被调用")

if __name__ == '__main__':
    running = True
    # 监听键盘热键
    keyboard.add_hotkey('ctrl+c', on_exit, args=(1, 2,))
    # 注册钩子函数
    atexit.register(on_exitee)

    while running:
        time.sleep(1)
        func('123')

posted @ 2024-09-02 14:59  darling331  阅读(15)  评论(0编辑  收藏  举报