Search code examples
pythonpyautogui

time.sleep alternatives for trials?


Are there any alternatives for time.sleep on python where I can run a function while timeouts?

Because I have these codes:

time.sleep(10)
pyautogui.locateCenterOnScreen('back.PNG')
pyautogui.click(120, 320)

What it does is that it runs the pyautogui after 10 seconds.

What I want is to run the pyautogui at the start and have trials for 10 seconds. If the image is not located within 10 seconds, then it will return error.


Solution

  • something like this?

    for _ in range(10):
        pos = pyautogui.locateCenterOnScreen('back.PNG')
        if pos: break
        time.sleep(1)
    
    if not pos: raise Exception('Where is this image?!')
    
    pyautogui.click(*pos)
    

    Note: it may take more time than 10 seconds, you could play with times instead

    A bit better if locateCenterOnScreen takes a while

    from datetime import datetime
    start = datetime.now()
    pos = None
    while (datetime.now() - start).total_seconds() < 10 and not pos:
        pos = pyautogui.locateCenterOnScreen('back.PNG')
    
    if not pos: raise Exception('Where is the image!!??')
    
    pyautogui.click(*pos)
    

    Or wrapped in a function

    def retry(action, max_secs=10):
        from datetime import datetime
        start = datetime.now()
        res = None
        while (datetime.now() - start).total_seconds() < max_secs:
            res = action()
            if res: return res
        raise Exception('Timeout!')
    
    pos = retry(lambda: pyautogui.locateCenterOnScreen('back.PNG'))
    pyautogui.click(*pos)
    

    Even "better" raising the exception outside of the function:

    def retry(action, max_secs=10):
        from datetime import datetime
        start = datetime.now()
        res = None
        while (datetime.now() - start).total_seconds() < max_secs:
            res = action()
            if res: break
        return res
    
    pos = retry(lambda: pyautogui.locateCenterOnScreen('back.PNG'))
    if not pos: raise Exception('Where is this image??!!')
    pyautogui.click(*pos)