Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect key press in python, where each iteration can take more than a couple of seconds?

Edit: The below answer to use keyboard.on_press(callback, suppress=False) works fine in ubuntu without any issues. But in Redhat/Amazon linux, it fails to work.

I have used the code snippet from this thread

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break

But the above code requires the each iteration to be executed in nano-seconds. It fails in the below case:

import keyboard  # using module keyboard
import time
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        print("sleeping")
        time.sleep(5)
        print("slept")
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        print("#######")
        break  # if user pressed a key other than the given key the loop will break
like image 326
Naren Babu R Avatar asked Mar 02 '20 13:03

Naren Babu R


People also ask

How do you wait for key press in Python?

In Python 2 use raw_input(): raw_input("Press Enter to continue...") This only waits for the user to press enter though. This should wait for a keypress.

How do you read a key in Python?

Here, we are using three methods to detect keypress in Python read_key() , is_pressed() and on_press_key() . The read_key() will read which key a user has pressed on the keyboard, and if it's that key which you wanted, in this case, p , it will print the message You pressed p .

How do you detect key press in Python?

If the user presses the key that matches the key specified as the first parameter of the on_press_key () function, it will only execute the function you have passed in as the second parameter. Detect KeyPress Using the pynput Module in Python The pynput module is used to detect and control input devices, mainly mouse and keyboard.

How does on_press_key() work in Python?

If the user presses the key that matches the key specified as the first parameter of the on_press_key () function, it will only execute the function you have passed in as the second parameter. The pynput module is used to detect and control input devices, mainly mouse and keyboard.

How to detect keypress In Tkinter in Python?

How to Detect keypress in Tkinter in Python. bind() functions are applied to an event where whenever an even is raised the corresponding handler will be called. root.bind("<Key>",key_pressed) Here a key_pressed function is called so we need to write a definition of this method.

How to break a loop in Python with keyboard?

More things can be done with keyboard module. You can install this module using pip install keyboard Here are some of the methods: This is gonna break the loop as the key p is pressed. It will wait for you to press p and continue the code as it is pressed. It needs a callback function.


2 Answers

You can make use of event handlers in keyboard module to achieve the desired result.

One such handler is keyboard.on_press(callback, suppress=False): Which invokes a callback for every key_down event. You can refer more at keyboard docs

Here is the code you can try:

import keyboard  # using module keyboard
import time

stop = False
def onkeypress(event):
    global stop
    if event.name == 'q':
        stop = True

# ---------> hook event handler
keyboard.on_press(onkeypress)
# --------->

while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        print("sleeping")
        time.sleep(5)
        print("slept")
        if stop:  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        print("#######")
        break  # if user pressed a key other than the given key the loop will break
like image 151
Shubham Sharma Avatar answered Oct 10 '22 08:10

Shubham Sharma


for people that might need this in the future, you can use keyboard.wait() which will basically wait untill the key gets pressed

keyboard.wait("o")
print("you pressed the letter o")

Do keep in mind that it blocks code execution after it. if you want to run code if the key is not being pressed i'd suggest doing

if keyboard.is_pressed("0"): 
    #do stuff
else: 
    #do other stuff
like image 43
Mana Avatar answered Oct 10 '22 09:10

Mana