用这个库keyboard,可以模拟按键,点击,组合键等,安装
pip install keyboard
用这个库pynput可以监听按键事件,安装:
pip install pynput
监听:
from pynput import keyboard
# 返回 False 关闭监听
def on_press(key):
if key == keyboard.Key.esc:
return False
try:
k = key.char # 监听单按键
except:
k = key.name
if k in ['1', '2', 'left', 'right']:
print('Key pressed: ' + k)
return False
listener = keyboard.Listener(on_press=on_press)
listener.start()
listener.join()