简体   繁体   中英

Break loop using hotkey

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM