How to close a while True loop instantly Python

Question:

I have a problem … How can i press P on my keyboard and close the entire program faster ( i would like instantly ) ? The script that i made runs in a loop ( Loop B ) and checks for an image on desktop, if it finds it it prints that it can see it, if not it prints that it cannot see it. Loop A is made to close the entire thing down with the press of P key. The problem is that the entire thing is too slow to close down … How can i make my script close faster ? 🙁

def loop_a():
    while True:
        a = keyboard.read_key()
        if a == 'p':
            print('Program has stopped...')
            break
        elif a != "p":
            print("Wrong key champ !")
            time.sleep(0.5)
def loop_b():
    while True:
        if pyautogui.locateOnScreen('image.png', confidence =.5) != None:
            print("I can see it")
            time.sleep(2)
        else:
            print("I am unable to see it")
            time.sleep(2)



if __name__ == '__main__':
    Thread(target=loop_a).start()
    Process(target=loop_b).start()
Asked By: Blockhead01

||

Answers:

Try sys.exit() function

import sys
def loop_a():
    while True:
        a = keyboard.read_key()
        if a == 'p':
            sys.exit('Program has stopped...')
        elif a != "p":
            print("Wrong key champ !")
            time.sleep(0.5)
Answered By: Kiran S
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.