pythonlisteneronclicklistenerpython-keyboard

Using a key listener to stop a loop


I'm trying to make python run a loop and when I press Shift+a the loop stops:

import pyautogui
import time
import random
from pynput.mouse import Button, Controller
from pynput import keyboard

COMBINATIONS =[
    {keyboard.Key.shift, keyboard.KeyCode(char='a')},
    {keyboard.Key.shift, keyboard.KeyCode(char='A')}
    ]

on = True
print(on)

mouse = Controller()
curent = set()

def execute():
    on = False
    pass

def on_press(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        curent.add(key)
        if any(all(k in curent for k in COMBO) for COMBO in COMBINATIONS):
            execute()

def on_release(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        curent.remove(key)


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

execute()

time.sleep(4)
while on == True:
    print('hi')

The problem is the code doesn't even get to the:

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

It stops if I put it after the while True loop the shortcut doesn't work, and if I put it inside the while True loop it pauses the loop.


Solution

  • You can simply use the add_hotkey method. Here is an example:

    import keyboard
    
    on = True
    
    def execute():
        on = False # The function you want to execute to stop the loop
    
    keyboard.add_hotkey("shift+a", execute) # add the hotkey
    
    while on:
        print("hi") # Do the code of your loop here