python检测键盘输入termios、等待按键超时检测
程序员文章站
2022-03-03 14:37:06
...
试了很多方案都不行或者不好用。win10+linux可以用的方法有pygame和termios
pygame方法参考:https://blog.csdn.net/qxqxqzzz/article/details/103315053
本文介绍termios方法,亲测可用
感谢:https://blog.csdn.net/qq_40930675/article/details/84667762
import sys
import tty
import termios
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)
while True:
key=readkey()
if key=='w':
print('w')
if key=='a':
print('a')
if key=='s':
print('s')
if key=='d':
print('d')
if key=='q':
break
超时两秒后显示超时,继续执行程序:
感谢:https://blog.csdn.net/dcrmg/article/details/82850457
import signal
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('waiting for press key...')
r = func(*args, **kwargs)
print('Key pressed.')
signal.alarm(0) # 关闭闹钟
return r
except RuntimeError as e:
callback()
return to_do
return wrap
def after_timeout(): # 超时后的处理函数
print("Time out!")
@set_timeout(2, after_timeout) # 限时 2 秒超时
def press_pause():
key = readkey()
return key
# 主程序中:
# from xxx import press_pause
# 检测按键,停止训练,保存当前模型和最佳模型
def train_one_epoch():
key = press_pause()
if key == 'p':
print('Save model and exit...')
// TODO
break
else:
pass
上一篇: theano扫盲
下一篇: python随机数的那些事儿