如何在Python中获取keycodes [英] How to obtain the keycodes in Python
问题描述
我必须知道按下了什么键,但不需要角色的代码,我想知道有人何时按下了A"键,即使获得的键是a"或A",等等所有其他键.
I have to know what key is pressed, but not need the code of the Character, i want to know when someone press the 'A' key even if the key obtained is 'a' or 'A', and so with all other keys.
我不能使用 PyGame 或任何其他库(包括 Tkinter).只有 Python 标准库.而且这必须在终端中完成,而不是图形界面.
I can't use PyGame or any other library (including Tkinter). Only Python Standard Library. And this have to be done in a terminal, not a graphical interface.
不需要字符代码.我需要知道关键代码.
NOT NEED THE CHARACTER CODE. I NEED TO KNOW THE KEY CODE.
例如:
ord('a') != ord('A') # 97 != 65
someFunction('a') == someFunction('A') # a_code == A_code
推荐答案
参见 tty标准模块.它允许使用 tty.setcbreak(sys.stdin).从 sys.stdin 读取单个字符将导致下一个按下的键盘键(如果它生成代码):
See tty standard module. It allows switching from default line-oriented (cooked) mode into char-oriented (cbreak) mode with tty.setcbreak(sys.stdin). Reading single char from sys.stdin will result into next pressed keyboard key (if it generates code):
import sys
import tty
tty.setcbreak(sys.stdin)
while True:
print ord(sys.stdin.read(1))
注意:解决方案仅适用于 Unix(包括 Linux).
在 Windows 上尝试 msvcrt.getche()/getwche()./me 无处可试...
On Windows try msvcrt.getche()/getwche(). /me has nowhere to try...
编辑 2:通过 ctypes.windll 使用 win32 低级控制台 API(请参阅SO 示例) 和 ReadConsoleInput
函数.您应该过滤掉按键 - e.EventType==KEY_EVENT
并查找 e.Event.KeyEvent.wVirtualKeyCode
值.可以在 找到应用程序示例(不是在 Python 中,只是为了获得一个想法)http://www.benryves.com/tutorials/?t=winconsole&c=4.
Edit 2: Utilize win32 low-level console API via ctypes.windll (see example at SO) with ReadConsoleInput
function. You should filter out keypresses - e.EventType==KEY_EVENT
and look for e.Event.KeyEvent.wVirtualKeyCode
value. Example of application (not in Python, just to get an idea) can be found at http://www.benryves.com/tutorials/?t=winconsole&c=4.
这篇关于如何在Python中获取keycodes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!