捕捉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