Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *