how to make program stop with a hotkey (outside the console)

Question:

I made an autoclicker and i can stop it by pressing b but only at the right timing. I didn’t find anything that would allow me to stop the program by pressing a button at any time without accessing the console

Here’s the program:

from time import sleep
import keyboard
import mouse

state=True
while state:
    if keyboard.is_pressed("b"):
        state=False
    else:
        mouse.click()
        sleep(1)
Asked By: pyleky11

||

Answers:

I already answered at Using a key listener to stop a loop

You can simply use the add_hotkey method.
Example:

import keyboard

state = True

def stop():
    state  = False # The function you want to execute to stop the loop

keyboard.add_hotkey("b", stop) # add the hotkey
Answered By: Lanfix
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.