1

I have a python program that takes control of the mouse. However, I would like to be able to cancel the program from running without wrestling the mouse away from the program. I tried to cancel using a keyboard shortcut like so:

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

However, this has the same issue, once the program has clicked away from the IDE I am unable to stop the program without fighting against the mouse. Is this even possible?

David
  • 769
  • 1
  • 6
  • 28
  • Could you clarify *auto clicking away from IDE*? Auto prefix means self. – Razzle Shazl Mar 11 '21 at 22:50
  • What are you using for the UI of the application? In general you'll be limited to what events that interface can provide about focus events. – MatsLindh Mar 11 '21 at 22:50
  • You can stop the script on some keypress. See [this question](https://stackoverflow.com/questions/33863921/detecting-a-keypress-in-python-while-in-the-background) – Yevhen Kuzmovych Mar 11 '21 at 22:51
  • @MatsLindh I am running it directly from PyCharm, this is not a production app. – David Mar 11 '21 at 22:52
  • @RazzleShazl in ```main``` I am using the ```payautogui``` to control the mouse so the IDE is no longer the main focus of the os, therefor pressing ctrl-c won't stop the program – David Mar 11 '21 at 22:54
  • Using the linked question from Yevhen you can listen for keypresses regardless of pycharm having focus; if you're on Windows that should work. – MatsLindh Mar 11 '21 at 23:04

1 Answers1

2

From PyAutoGUI it looks like you can configure a failsafe.

As a safety feature, a fail-safe feature is enabled by default. When a PyAutoGUI function is called, if the mouse is in any of the four corners of the primary monitor, they will raise a pyautogui.FailSafeException. There is a one-tenth second delay after calling every PyAutoGUI functions to give the user time to slam the mouse into a corner to trigger the fail safe.

Fail safe appears to be enabled by default. Verify that pyautogui.FAILSAFE == True.

In code: Try changing KeyboardInterrupt to pyautogui.FailSafeException.

At runtime: Within .1s of your program calling a pyautogui function, move your mouse to the corner of your screen. I expect this to trigger your sys.exit(0).

Razzle Shazl
  • 1,287
  • 1
  • 8
  • 20