Reputation: 27
My code should press "p" twice, after pressing the letter "u" on the keyboard, . This also works. But when I press "u" twice in quick succession, the code hangs up and the function somehow keeps calling itself, even though I don't press "u" at all. Does anyone know what could be the reason for this?
from pynput.keyboard import Listener
import keyboard # using module keyboard
import time
def on_press(key): # The function that's called when a key is pressed
if keyboard.is_pressed('u'): #'u' is pressed
keyboard.press('p')
keyboard.release('p')
time.sleep(0.01)
keyboard.press('p')
keyboard.release('p')
time.sleep(1)
else:
pass
with Listener(on_press=on_press) as listener: # Create an instance of Listener
listener.join() # Join the listener thread to the main thread to keep waiting for keys
Upvotes: 0
Views: 255
Reputation:
It's probably because the code under the keyboard.is_pressed('u')
takes 1.001 seconds to execute (or slightly more) because of the time.sleep
calls. If you press U twice in less than 1.001 seconds, it is breaking because the function can't finish before you call it again.
Upvotes: 1