Question

I am using Sikuli the OCR testing library. In my Python script I am looking for one of two possible images to appear. When one of them does appear, if chooses that object.

However, I would like for the script to end. It doesn't. I've tried quit() and exit() but that isn't doing it. It is working fine, beside the stop of the while loop and completing the script.

while True:
    if exists ("lose.png"):
        click ("lose.png")
        print ("***** YOU LOSE! *****")
    if exists ("win.png"):
        click ("win.png")
        print ("***** YOU WIN! *****")
    StopIteration

quit()
Was it helpful?

Solution

You can exit any loop with break:

while True:
    if exists ("lose.png"):
        click ("lose.png")
        print ("***** YOU LOSE! *****")
        break

    if exists ("win.png"):
        click ("win.png")
        print ("***** YOU WIN! *****")
        break

If neither of the if statements evaluate to True, the loop continues.

StopIteration is an exception, usually raised by iterators to signal that they are done. Most Python code that uses it only needs to catch that exception, but if you wanted to raise it, use a raise StopIteration() statement. There is no point in doing so here; your script is not being run as an iterator and the StopIteration exception will not have the desired effect.

OTHER TIPS

You can always do this:

status = TRUE
while status:
        if exists ("lose.png"):
            click ("lose.png")
            print ("***** YOU LOSE! *****")
            status = FALSE
        if exists ("win.png"):
            click ("win.png")
            print ("***** YOU WIN! *****")
            status = FALSE
        StopIteration
    
    quit()

In Python, break is used to exit loops. To exit the script, use sys.exit(). So:

while True:
    if exists ("lose.png"):
        click ("lose.png")
        print ("***** YOU LOSE!*****")
    if exists ("win.png"):
        click ("win.png")
        print ("***** YOU WIN!*****")
    break // Exit the loop
import sys; sys.exit() // Close the program
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top