How can I stop/unbind a pynput listener?

43 Views Asked by At

I'm making a translator and I want to have 2 shortcuts, one to translate and one to exit the program:

def on_exit_hotkey():
    listener.stop()
    exit()

print('\n-- Press CTRL+T on keyboard to translate.')
print('-- Press SHIFT+ESC on keyboard to exit.\n')

listener = keyboard.GlobalHotKeys({'<ctrl>+t': on_translate_hotkey, '<shift>+<esc>': on_exit_hotkey})
listener.start()
listener.join()

The problem is that when I press SHIFT + ESC the listener still runs and the program doesn't stop. How would I fix that?

1

There are 1 best solutions below

0
On

To stop the listener, just return False from the function. I wrote my code in a slightly different format, but it should still work for you:

from pynput.keyboard import Listener

def on_press(key):
    if key.char == 'j': #I chose the key j but it can be anything
        return False #pynput listener stops if function returns False
    #else do whatever you want with the key

with Listener(on_press=on_press) as listener:
    listener.join()