Am trying to create a hotkey to stop my script, this is my code so far.
import time
import keyboard
running = True
def stop(event):
global running
running = False
print("stop")
# press ctrl esc to stop the script
keyboard.add_hotkey("ctrl esc", lambda: stop)
while running:
time.sleep(2)
print("Hello")
time.sleep(2)
CodePudding user response:
add_hotkey expects a callback as the second argument, so you must pass it the stop function, on the other hand, when the callback is invoked, no event is passed.
A better solution than using a boolean variable is to use threading.Event since this is thread-safe since the callback is invoked in a secondary thread.
import threading
import time
import keyboard
event = threading.Event()
def stop():
event.set()
print("stop")
keyboard.add_hotkey("ctrl esc", stop)
while not event.is_set():
time.sleep(2)
print("Hello")
time.sleep(2)