Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the simply-static domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/html/wp-includes/functions.php on line 6121
捕捉系统按键ctrl-c等

捕捉系统按键ctrl-c等

捕捉Ctrl-C键盘事件

import time
import signal
def signal_handler(signal,frame):
    print('You pressed Ctrl+C!')
signal.signal(signal.SIGINT,signal_handler)
print('Press Ctrl+C')
for x in range(1,100):
    time.sleep(2)
    print(x)

import time
if __name__ == "__main__":
    try:
        time.sleep(10)
    except KeyboardInterrupt:
        print("Application exit!")
# 自定义信号处理函数
def my_handler(signum, frame):
    global stop
    stop = True
    print("终止")
# 设置相应信号处理的handler
signal.signal(signal.SIGINT, my_handler)    #读取Ctrl+c信号
stop = False
while True:
    try:
        #读取到Ctrl+c前进行的操作
        if stop:
            # 中断时需要处理的代码
            pass
#            break    #break只能退出当前循坏
            #中断程序需要用 raise
    except Exception as e:
        print(str(e))
        break