Malachi Bazar Malachi Bazar - 1 year ago 72
Python Question

How do I have a fail safe command in python

So I'm trying to make a program that randomly places my mouse in specific areas in python, and I'm still testing it so it can get a bit crazy. I was wondering if it were possible to make a fail safe command that would terminate the program if the key or command were entered.

Since the program is clicking and moving around on another window on my computer it deselects the window python is running in, which make the "Keyboard Interrupt" fail to work.

Here's the program:

import pyautogui
import random
import time
time.sleep(6)#gives you time to click the right window

while True:
x = random.randint(239, 1536)#randomizes the position of the mouse

pyautogui.moveTo(x,663) #moves the mouse to position

pyautogui.doubleClick() #fires the gun in game twise

time.sleep(1); pyautogui.doubleClick()#gives time for the game to
#catch up with the mouse and fires gun
pyautogui.doubleClick() #fires gun twice again

except Keyboard Interrupt:
print ('Yup')

And if there is anything wrong with the way I'm coding please tell me. I'm still new to coding so any tips would be awesome.

Answer Source

What you are looking to do is use a sys.exit() in your Exception.

Try this:

import sys

    # all your code
except KeyboardInterrupt: