Categories
Python Answers

How to detect keyboard input in a script from the terminal with Python?

Spread the love

Sometimes, we want to detect keyboard input in a script from the terminal with Python.

In this article, we’ll look at how to detect keyboard input in a script from the terminal with Python.

How to detect keyboard input in a script from the terminal with Python?

To detect keyboard input in a script from the terminal with Python, we can use pynput.

To install it, we run

pip install pynput

Then we use it by writing

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        return False

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

to define the on_press and on_release functions to listen for keypresses and key up events.

We get the value pressed from the key parameter.

And then we add the listeners with the keyboard.Listener class with on_press set to on_press and on_release set to on_release.

Then we call listener.join to add them as listeners.

Conclusion

To detect keyboard input in a script from the terminal with Python, we can use pynput.

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 *