Search code examples
pythonkeyboardcommand-line-interface

How would I wait for a SINGLE key press in python


I need to pause the program until the user presses a key, and then it should return whatever key was pressed.

Most places I look show one of two solutions:

# This doesn't work with what I need for obvious reasons
return input("Enter key here >>> ")

# but sometimes they'll use something like this:
import keyboard
while True:
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN:
        return event.name

But the second example, while it does only return the key when it's first pressed down as expected, there's an issue with this approach, in that if I put a regular input after using this bit of code (key = input("Enter key here >>> ")), the key that's pressed gets typed in to the input.

How would I only return the key when it's first pressed down (not held), and also use up that key press (not have the key press do anything else)?


Solution

  • If you use suppress=True, the key press is not passed on to the system, so it won’t be stored in the input buffer. This prevents the key from appearing in any following input() calls.

    import keyboard
    while True:
        event = keyboard.read_event(suppress=True)
        if event.event_type == keyboard.KEY_DOWN:
            return event.name