Home > Back-end >  Break loop using hotkey
Break loop using hotkey

Time:03-01

There are hundreds of similar questions but none of them appear to be a solution in my case. My code is shaped in this way

def iterative_func():
    # do things
while True:
    iterative_func()

Then I would like it to stop when I press a hotkey let's say 'ctrl k'. I tried pynput but the listener is not applicable since it waits for an Input and the rest of the script (iterative_func()) won't run, in my case the script should continuously run until I press some hotkey. Also the solution

while True:
    try:
        iterative_func()
    except KeyboardInterrupt:
        break

doesn't work for me (I don't know why, but maybe it's because I'm running VSCode), anyway it's not code I want to implement because the script will be deployed as a .exe file.

PS. I cannot import Key and Controller from pynput, it prompts an error and I have no clue on how to fix this so also solutions using these should be avoided.

CodePudding user response:

I tried pynput but the listener is not applicable since it waits for an Input and the rest of the script (iterative_func()) won't run

I can shed some light on how to overcome this problem, which made you optout pynput. See the below approach:

from pynput import keyboard

running = True  # flag on loop runs


def stop_run():  # function to stop the program
    global running
    running = False


# register a hotkey, and call stop_run() when it is pressed
with keyboard.GlobalHotKeys({'<ctrl> k': stop_run}) as h:
    while running:
        print("Running ... ")

This will run your code and wait for hotkey to stop the loop by a flag.

  • Related