pythonkeyboard-shortcutspynput

Listen for keyboard shortcut ESC + ESC then run some code


I want to listen for the keyboard shortcut ESC + ESC and then run some code. What I mean is that, if the user presses the ESC key twice, then some code should get executed.

I tried the following code, but it doesn't work:

from pynput import keyboard

pressed = set()

def run(s):
    if (s == "switch"):
        print("Hello World!")

def on_press(key):
    pressed.add(key)
    print(pressed)
    if (pressed == 27):
        print("Hello World!")

def on_release(key):
    if key in pressed:
        pressed.remove(key)

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

Please help me using the library that best serves my purpose.


Solution

  • import time
    
    from pynput import keyboard
    
    
    class DoubleEscapeListener:
        def __init__(self):
            self.pressed = set()
            self.last_esc_time = 0
            self.double_press_threshold = 0.5  # Time within which two ESC keys must be pressed.
    
        def run(self):
            print("Hello World!")
    
        def on_press(self, key):
            if key == keyboard.Key.esc:
                current_time = time.time()
                if current_time - self.last_esc_time < self.double_press_threshold:
                    self.run()
                self.last_esc_time = current_time
    
        def on_release(self, key):
            if key in self.pressed:
                self.pressed.remove(key)
    
        def listen(self):
            with keyboard.Listener(on_press=self.on_press, on_release=self.on_release) as listener:
                listener.join()
    
    
    if __name__ == "__main__":
        listener = DoubleEscapeListener()
        listener.listen()
    

    This code will run the run method when the ESC key is pressed twice within the double_press_threshold time. You can adjust this threshold according to your needs.