zhlzhl zhl
zhlzhl zhl

Reputation: 13

How to stop a loop with keyboard.add_hotkey, while this loop is started by keyboard.add_hotkey?

The following code works perfectly, the loop can be stop by pressing esc:

import time
import keyboard

run = 1

def end():
    global run
    run = 0
    print(run)

def do_stuff():
    while run:
        print('running')
        time.sleep(0.5)

keyboard.add_hotkey('esc', end)
do_stuff()

But if I start this loop with another add_hotkey, I cannot stop it with esc anymore.

import time
import keyboard

run = 1

def end():
    global run
    run = 0
    print(run)

def do_stuff():
    while run:
        print('running')
        time.sleep(0.5)

keyboard.add_hotkey('esc', end)
# do_stuff()

keyboard.add_hotkey('enter', do_stuff)
keyboard.wait()

What should I do to stop this loop? I tried to replace the while run: with while not keyboard.is_pressed('esc'):. It can stop the loop if I hold the esc for a while. But it doesn't seem like a good solution.

======================= updates: the following works:

import keyboard
import threading

run = 1

def end():
    global run
    run = 0
    print(run)

def do_stuff():
    while run:
        print('running')
        time.sleep(0.5)

def new_do_stuff():
    t = threading.Thread(target=do_stuff, name='LoopThread')
    t.start()


keyboard.add_hotkey('esc', end)
keyboard.add_hotkey('enter', new_do_stuff)
keyboard.wait('esc')

Upvotes: 1

Views: 625

Answers (1)

Kneidl1202
Kneidl1202

Reputation: 51

Since in the second example you enter the do_stuff() loop through the hotkey and never leave the do_stuff() loop, the system is still captured in the hotkey command and is not listening for hotkeys anymore. You would have to find a way to leave the loop after the keyboard.add_hotkey('enter', do_stuff) command and enter it externally through another way, so the system listens for hotkey-entries again.

I'm not aware of the context you're using this in, but using some sort of a main-loop, that does nothing but wait for a flag to be set (it should be set when you get the hotkey interrupt) and then enters the do_stuff() loop seems like a way to solve it.

Upvotes: 1

Related Questions