What is the easiest way to detect key presses in python 3 on a linux machine?


Right now I’m trying to make a small code with a raspberry pi and and a makey makey. The makey makey is a small board that acts as a usb keyboard when certain contacts are powered. My question is what is the easiest way to detect those keypresses inside a python script. I understand using the GPIO pins would be easier, but right now I’m looking for this. I have seen examples such as using using getch() from msvcrt (which from what I understand is windows only,) using pygame.key, and using getKey. Which of theses is easiest to use? Are there any that can detect a key being pressed and a key being released?

Pseudo code:

import whatever needs importing    

if the "W" key is pressed:
   print ("You pressed W")

elif the "S" is pressed:
    print ("You pressed S")

and so on. Thanks.

Asked By: montainz09



Using a good lightweight module curtsies you could do something like this (taken from their examples/ directory):

from curtsies import Input

def main():
    with Input(keynames='curses') as input_generator:
        for e in input_generator:

if __name__ == '__main__':

So pressing keys on your keyboard gives you something like this:


curtsies is used by bpython as a low level abstraction of terminal-related stuff.

The basic problem of decoding the input is that in different terminals and terminal emulator programs like xterm or gnome-terminals physically same keys produce different keycode sequences. That’s why one needs to know which terminal settings should be used to decode input. Such a module helps to abstract from those gory details.

Answered By: user3159253

This is a simple loop that will put stdin in raw mode (disabling buffering so you don’t have to press enter) to get single characters. You should do something smarter (like a with statement to disable it) but you get the idea here:

import tty
import sys
import termios

orig_settings = termios.tcgetattr(sys.stdin)

x = 0
while x != chr(27): # ESC
    print("You pressed", x)

termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)    

I think you’d have to loop to detect key releases in Python.

ETA some more explanation:

On Linux, input to your program will be line buffered. This means that the operating system will buffer up input until it has a whole line, so your program won’t even see anything the user typed until the user also hits ‘enter’. In other words, if your program is expecting the user to type ‘w’ and the user does this, ‘w’ will be sitting in the OS’s buffer until the user hits ‘enter’. At this point the entire line is delivered to your program so you will get the string “wn” as the user’s input.

You can disable this by putting the tty in raw mode. You do this with the Python function tty.setcbreak which will make a call down the tty driver in linux to tell it to stop buffering. I passed it the sys.stdin argument to tell it which stream I wanted to turn buffering off for1. So after the tty.setcbreak call, the loop above will give you output for every key the user presses.

A complication, though, is that once your program exits, the tty is still in raw mode. You’ll generally find this unsatisfying since you don’t get any of the power that modern terminal settings offer (like when you use control or escape sequences). For example, notice that you might have trouble exiting the program with ctrl-C. Consequently you should put the terminal back into cooked mode once you are done reading input characters. The termios.tcsetattr call simply says “put the terminal back the way I found it”. It knows how to do this by first calling termios.tcgetattr at the beginning of the program which is saying “tell me all the current settings for the terminal”.

Once you understand all that, you should easily be able to encapsulate the functionality in a function that suits your program.

1 stdin is the stream that input comes to you from the user. Wikipedia can tell you more about standard streams.

Answered By: Turn

Since your question states that you are using a Raspberry Pi and a USB HID keyboard peripheral, but does not specify whether or not you have the Pi configured to boot into text or graphical mode where you will be running your script, I would suggest using libinput which will work in either case.

You can use libinput’s python bindings to read keyboard (and most other input devices) events directly from the kernel.

pip3 install python-libinput

The interface to this subsystem is exposed through the character devices which usually live in /dev/input/. They are managed by udev rules which create one or more character devices per attached input device, and are added and removed dynamically when, for example, a USB keyboard is attached or unplugged, or a Bluetooth mouse connects or disconnects.

Libinput handles for you the task of opening and reading from all attached input devices, and opening and closing devices when they are added and removed, respectively.

Using libinput from python to read key events would look like this:

import libinput

def read_key_events():
    # init libinput
    li = libinput.LibInput(udev=True)
    # loop which reads events
    for event in li.get_event():
        # test the event.type to filter out only keyboard events 
        if event.type == libinput.constant.Event.KEYBOARD_KEY:
            # get the details of the keyboard event
            kbev = event.get_keyboard_event()
            kcode = kbev.get_key() # constants in  libinput.define.Key.KEY_xxx
            kstate = kbev.get_key_state() # constants   libinput.constant.KeyState.PRESSED or .RELEASED 
            # your key handling will look something like this...
            if kstate == libinput.constant.KeyState.PRESSED:
                print(f"Key {kcode} pressed") 
            elif kstate == libinput.constant.KeyState.RELEASED:
                if kbev.get_key() == libinput.define.Key.KEY_ENTER:
                    print("Enter key released")
                elif kcode == libinput.define.Key.KEY_SPACE:
                    print("Space bar released")
                    print(f"Key {kcode} released")

One minor gotcha to be aware of is that udev is commonly configured to set permissions on the event devices it creates in /dev/input/ to allow access only from users who are members of a special supplementary ‘input’ group, since to allow unrestricted access to raw user key and mouse input would be a major security flaw. As such, o if running this throws an error during the libinput initialisation, you may need to add input to your user’s supplementary groups by running:

sudo usermod -G input -a "${USERNAME}"
Answered By: Victor Condino