Search code examples
pythontimesleeppyautogui

Catch pyautogui.FailSafeException whilst program is waiting to execute next line of code


I am using pyautogui inside an infinite while loop to iteratively move my mouse around the screen every 10 seconds. pyautogui implements a failsafe, which throws pyautogui.FailSafeException if the mouse is in the top left corner of the screen - (0, 0) coordinates.

I implement this simple logic using time.sleep() and the following code:

import time 

try:
    while True:
        for coords in [(100, 100), (1000, 100), (1000, 1000), (100, 1000)]:
            pyautogui.moveTo(coords)
            time.sleep(10)  # <- I want to be catching exceptions during this time period as well as when the code is actively running 
except pyautogui.FailSafeException:
    # DO SOMETHING

However, if I move my mouse to the top left corner during the 10 seconds of sleep, the exception does not get caught until the 10 seconds of sleep are over (obviously!). My goal is to immediately catch this exception, rather than having to wait until the end of these 10 seconds.

So my question is - is there a function that will allow me to catch exceptions whilst the code is "doing nothing" for 10 seconds?


Solution

  • You can poll to check if the time has expired rather than use a blocking sleep command. While polling, you can check the position of the mouse. If the position of the mouse is (0,0) you can then break out instantly.

    Here is the code:

    Code:

    import time 
    import pyautogui
    
    def sleep_for(secs):
        current_time = time.time()
        end_time = time.time() + secs
        
        while current_time < end_time:
            current_time = time.time()
            if pyautogui.position() == (0,0):
                print("Fail Safe Exit")
                break
         
    try:
        while True:
            for coords in [(100, 100), (1000, 100), (1000, 1000), (100, 1000)]:
                pyautogui.moveTo(coords)
                sleep_for(10) 
                    
                 
    except pyautogui.FailSafeException:
        # DO SOMETHING
        pass
    

    The sleep_for() function is used to monitor the mouse position while waiting for 10 seconds. If the mouse moves to position (0,0) then it will break out of the while loop instantly.