Key Listeners in python?

ollien picture ollien · Aug 12, 2012 · Viewed 97.9k times · Source

Is there a way to do key listeners in python without a huge bloated module such as pygame?

An example would be, when I pressed the a key it would print to the console

The a key was pressed!

It should also listen for the arrow keys/spacebar/shift key.

Answer

Xiangrui Li picture Xiangrui Li · Mar 30, 2017

I was searching for a simple solution without window focus. Jayk's answer, pynput, works perfect for me. Here is the example how I use it.

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys