How to make KeyboardInterrupt outside of console?

Question:

I’m using PyAutoGui for automation of adding data to certain fullscreen app. Problem is, when I try to Alt+Tab back to my IDE it constantly brings app back to front and messes up my code by pasting data there. I need a way to either prevent script from working when I press Alt+Tab or when window comes out of focus. How do I do that?

I tried:
Ctrl-C
Ctrl-Pause

import _thread

def input_thread(a_list):
    raw_input()             # use input() in Python3
    a_list.append(True)
    
def do_stuff():
    a_list = []
    _thread.start_new_thread(input_thread, (a_list,))
    while not a_list:
        stuff()
Asked By: RickStead

||

Answers:

You can use the pyautogui.FAILSAFE property to set a fail-safe mechanism that will stop the script from running when the mouse cursor is moved to the top-left corner of the screen. This can be done by setting the pyautogui.FAILSAFE property to True before you start using the pyautogui library, like this:

import pyautogui

# Set the fail-safe mechanism
pyautogui.FAILSAFE = True

# Your automation code goes here

Alternatively, you can use the pyautogui.onFailSafe function to specify a custom function to be called when the fail-safe mechanism is triggered. This can be useful if you want to do something more than just stopping the script, such as logging an error message or saving the state of your automation.

Here’s an example of how you can use the pyautogui.onFailSafe function:

import pyautogui

def onFailSafe():
  print('The fail-safe mechanism has been triggered!')
  # Add your custom code here

# Set the fail-safe mechanism and specify the custom function to call
pyautogui.FAILSAFE = True
pyautogui.onFailSafe(onFailSafe)

# Your automation code goes here

Note that the pyautogui.onFailSafe function must be called after setting the pyautogui.FAILSAFE property to True. Also, the onFailSafe function must be defined before calling pyautogui.onFailSafe so that it can be passed as an argument.

Answered By: Dario Coronel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.