Menu Close

How to poll the keyboard to detect a keypress in Python?

Sometimes, we want to poll the keyboard to detect a keypress in Python.

In this article, we’ll look at how to poll the keyboard to detect a keypress in Python.

How to poll the keyboard to detect a keypress in Python?

To poll the keyboard to detect a keypress in Python, we can use the pynput library.

To install it, we run

pip install pynput

Then we write

from pynput.keyboard import Key, Listener

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

to add event listeners for key presses and releases.

We create a Listener object using the on_press and on_release functions to listen for key presses and key releases respectively.

And we call listener.join to collect events until released.

We get the key pressed from the key parameter in each event handler function.

Conclusion

To poll the keyboard to detect a keypress in Python, we can use the pynput library.

Posted in Python, Python Answers