Wait for Key Press in Python

In this tutorial, we will learn how to wait for a key press in input for a specific time in Python. There are certain instances during development when you have to deploy the feature while waiting for the user to press the key or anywhere else to make your code more user-interactive. In such circumstances, “Wait for Key Press” methods are essential.

Using input() function

This function will wait for the user to press the key. I am adding the statement in the input function so that I know that I have to press a key to continue. You can modify the statement according to your needs.

input("Press any key to continue")

print("You have pressed the key")

taking input in Python

taking input in Python

As you can see in the image, the cell is running and waiting for the user to press any key. After pressing the key, the print statement will work.

Python program to wait for a specific time to take input from the user

In the first method, the code will keep on running till the user doesn’t press any key. But this practice will crash the system. So, to prevent this, better practice is to apply a timer of 10 seconds or 20 seconds, or according to your requirement, and after the stipulated time, the code automatically gets terminated.
We will use the time and keyboard library for time and key-related tasks, respectively. The keyboard library requires administrator permission, so make sure to run the Python file using the following:

sudo python filename.py

To write efficient code and improve your coding practice, I suggest noting the logic, making pseudocode, and implementing it. Let’s follow the same in our case, too.

  • We need a boolean variable to store whether the key is pressed or not in the entire run. So, declare this variable globally to have access anywhere and modify it.
  • Use the keyboard.on_press() function to save the event of pressing any key. If the key will be pressed, we have to set the boolean variable key_pressed=True.
  • We will print that the key is pressed based on this boolean variable. Now, one situation is the user can press the key in between the time interval. So, we have to implement the for loop to check the entire interval. Here, I am checking at 0.1 intervals. This will enhance the CPU usage, so I am using the time.sleep() function to reduce it.
  • Use the exit(0) function to terminate the code.
import time
import keyboard

# Boolean variable
key_pressed = False

def on_key_event():
    global key_pressed
    key_pressed = True

def wait_for_key_press(timeout_duration):
    global key_pressed
    print("Waiting for a key press for {} seconds...".format(timeout_duration))
    
    # Taking the input of pressing key by the user. This is considered as an event.
    keyboard.on_press(on_key_event)

    # Check every 0.1 seconds if a key has been pressed
    for _ in range(int(timeout_duration * 10)):
        if key_pressed:
            print("Key pressed!")
            return True
        time.sleep(0.1)  # Sleep for 0.1 second intervals to reudce the CPU usage.

    print("No key was pressed in {} seconds. Exiting...".format(timeout_duration))
    return False

if not wait_for_key_press(10):
    exit(0)  # Exit the program if no key was pressed within the timeout

Run this program to see the output. It will wait for the specific mentioned time to take input from the user.

Leave a Reply

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