Search code examples
pythonpyautogui

How to close a while True loop instantly Python


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()

Solution

  • 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)