Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading