import sys, tty, os, termios
def getkey():
old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
try:
while True:
b = os.read(sys.stdin.fileno(), 3).decode()
if len(b) == 3:
k = ord(b[2])
else:
k = ord(b)
key_mapping = {
127: 'backspace',
10: 'return',
32: 'space',
9: 'tab',
27: 'esc',
65: 'up',
66: 'down',
67: 'right',
68: 'left'
}
return key_mapping.get(k, chr(k))
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
try:
while True:
k = getkey()
print("Detected key: {}".format(k))
if k == 'esc':
quit()
else:
print(k)
except (KeyboardInterrupt, SystemExit):
os.system('stty sane')
print('stopping.')
测试和输出:
>>> python3 test.py
Detected key: a
a
Detected key: s
s
Detected key: d
d
Detected key: f
f
Detected key: right
right
Detected key: left
left
Detected key: space
space
Detected key: tab
tab
stopping.
您可以尝试以下代码。它不包含第三方模块
代码:
测试和输出:
注意:如果您能够使用外部Python模块,我建议使用
pynput
或keyboard
Python模块。链接:https://github.com/boppreh/keyboard,https://github.com/moses-palmer/pynput相关问题 更多 >
编程相关推荐