Search code examples
python-3.xopencvpynput

how to wait until a hotkey is pressed in python3 without the terminal window needing to be up?


I would like some sort of blockade that waits until a certain hotkey is pressed. I would be happy with something like input('Press Enter to continue') except for the fact that that would require my screen be on the terminal page, I would like this to pick up my keys while im focused on another window.

Luis Jose's solution from here seemed like it might work adn its good that im already using opencv for smoethign else so its imported: How to kill a while loop with a keystroke? However running the code does nothing for me and it doesn't pick up the fact that i pressed 'a' and just stays int he loop forever.

import cv2

while (1):
    k=0xFF & cv2.waitKey(1)
    if k == ord('a'):
        break

Solution

  • The above code will not work as cv2.waitKey is designed to work when a display window is created using cv2.imshow and you want to stop the display. This makes sense as opencv was designed to be a image and video processing toolbox. You can try using the pynput package.

    from pynput import keyboard
    
    def on_press(key):
        try:
            print('alphanumeric key {0} pressed'.format(
                key.char))
        except AttributeError:
            print('special key {0} pressed'.format(
                key))
    
    def on_release(key):
        print('{0} released'.format(
            key))
        if key == keyboard.Key.esc:
            # Stop listener
            return False
    
    # Collect events until released
    with keyboard.Listener(
            on_press=on_press,
            on_release=on_release) as listener:
        listener.join()
    

    When you press the esc key the above code terminates. For more details about the package you can visit: pynput project page