Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading