How to obtain the keycodes in Python

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))

Note: solution is Unix (including Linux) only.

Edit: On Windows try msvcrt.getche()/getwche(). /me has nowhere to try…


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.

Leave a Comment