python 检测键盘按键,随时停止程序
程序员文章站
2022-05-27 10:36:52
...
不是我原创的,但是原文我已经找不到在哪了。侵删。
很好用的函数。Linux ubuntu下可用。可能不适用于win10环境和多进程(非终端环境)环境。多进程的按键停止方法见:https://blog.csdn.net/qxqxqzzz/article/details/105642875
import sys
import tty
import termios
import signal
import time
def readchar():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def readkey(getchar_fn=None):
getchar = getchar_fn or readchar
c1 = getchar()
if ord(c1) != 0x1b:
return c1
c2 = getchar()
if ord(c2) != 0x5b:
return c1
c3 = getchar()
return chr(0x10 + ord(c3) - 65)
def set_timeout(num, callback):
def wrap(func):
def handle(signum, frame): # 收到信号 SIGALRM 后的回调函数,第一个参数是信号的数字,第二个参数是the interrupted stack frame.
raise RuntimeError
def to_do(*args, **kwargs):
try:
signal.signal(signal.SIGALRM, handle) # 设置信号和回调函数
signal.alarm(num) # 设置 num 秒的闹钟
print('press e to stop this program...')
r = func(*args, **kwargs)
print('Detected Key pressed.\n')
signal.alarm(0) # 关闭闹钟
return r
except RuntimeError as e:
callback()
return to_do
return wrap
def after_timeout(): # 超时后的处理函数
print("No key pressed!\n")
@set_timeout(2, after_timeout) # 限时 2 秒超时
def press_pause():
key = readkey()
return key
if __name__ == '__main__':
while True:
# 检测按键,停止训练,保存当前模型和最佳模型
key = press_pause()
if key != None:
print(key+'\n')
if key == 'e':
print('exit')
break
time.sleep(1)