Reputation: 1823
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
try:
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) #gives time for the game to
pyautogui.doubleClick() #catch up with the mouse and fires gun
pyautogui.doubleClick() #fires gun twice again
except KeyboardInterrupt:
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.
Upvotes: 3
Views: 43020
Reputation: 3
this should work, whenever you click the key it will break the loop, install the module keyboard with
pip install keyboard
if keyboard.is_pressed('q'):
break
Upvotes: 0
Reputation: 975
PyAutoGUI also has a fail-safe feature. Moving the mouse cursor to the upper-left corner of the screen will cause PyAutoGUI to raise the pyautogui.FailSafeException exception.
Your program can either handle this exception with try and except statements or let the exception crash your program. Either way, the fail-safe feature will stop the program if you quickly move the mouse as far up and left as you can.
>>>import pyautogui
>>>pyautogui.FAILSAFE= True
By default FAILSAFE is True, and you can also disable it.
>>>pyautogui.FAILSAFE = False
Upvotes: 17
Reputation: 26600
What you are looking to do is use a sys.exit() in your Exception.
Try this:
import sys
try:
# all your code
except KeyboardInterrupt:
sys.exit()
Upvotes: 6