pythonpyautogui

How to use KeyboardInterrupt with other exceptions?


I'm trying to use KeyboardInterrupt along with other errors but it doesn't seem to be working. (I have pyautogui and time imported already.) New to python btw.

while true
  try:
      x, y = pyautogui.locateCenterOnScreen('default.png')                                                 
      pyautogui.click(x, y)
      print (x, y)
      time.sleep(0.5)

  except ImageNotFoundException:
      print ("Nope nothing there. Try number:", tries)
      time.sleep(1)

  except KeyboardInterrupt:
      print("Manual shutdown activated...")
      time.sleep(1)
      break;

Solution

  • Here is a complete example of what you have with some time exaggerations:

    import time
    
    while True:
        print('outside try')
        time.sleep(1)  # interrupting here won't be caught
        try:
            print('inside try')  # interrupting here will be caught (small window)
            with open('nonexistent.file') as f:  # This will go to FileNotFoundError
                pass
        except FileNotFoundError:
            print('file not found')
            time.sleep(.5)  # interrupting here won't be caught
        except KeyboardInterrupt:
            break
        print('outside try')
        time.sleep(1)  # interrupting here won't be caught
    
    print('exiting')
    

    Wrap exactly the areas you expect to catch. Put the KeyboardInterrupt try around the whole while loop, and the FileNotFoundError try around opening the file:

    try:
        while True:
            try:
                with open('nonexistent.file') as f:
                    pass
            except FileNotFoundError:
                print('file not found')
    except KeyboardInterrupt:
        print('exiting')