Python Forum

Full Version: If error sleep and then try again from there
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey!

So I wrote a long code which is using the pyautogui locatonOnScreen and then center and then click functions. Basically it has a picture of a button which it finds on screen and clicks there. I have around 40 of these in the code to find specific buttons in a program. My problem is that sometimes the script goes too fast and it already tries to search for the image even though technically it has not appeared yet. We are talking about fractions of a second but randomly it give me the "picture not found" error depending on how fast my computer is at the moment and where the code gets to.

So my question is, can I somehow tell the whole code to use "time.sleep(3)" (wait 3 seconds before proceeding) if it encounters and error during the code and continue from the same line without adding a "try and else" after every line?
Sure.
import time

def do_work():
    # whatever you're doing

while True:
    try:
        do_work()
    except:
        time.sleep(3)
Wow, i never knew you could do it this way! Thank you for the help!