I'm on Windows 10, VSCode, Python 3.9
My program is an infinite loop that moves my mouse around the screen. Currently my code allows me to exit the program in between mouse movements, but not mid mouse movement. I want to be able to break at anytime with a keypress.
import time
import pyautogui
import keyboard
pyautogui.FAILSAFE = False
pyautogui.PAUSE = 0
var = 1
while var == 1:
if keyboard. is_pressed('b'):
break
else:
pyautogui.moveTo(384, 216, 0.5)
if keyboard. is_pressed('b'):
break
else:
pyautogui.moveTo(1536, 216, 0.5)
if keyboard. is_pressed('b'):
break
else:
pyautogui.moveTo(1536, 864, 0.5)
if keyboard. is_pressed('b'):
break
else:
pyautogui.moveTo(384, 864, 0.5)
This is my first question on here so please let me know if my formatting is wrong. Also if anyone has recommendations to make my code prettier I will gladly accept.
As mentioned in comments, threading is a good way to go:
import threading
import time
import keyboard
def move_mouse(arg): # simulate a blocking function call, like pyautogui.moveTo()
print("moving {}".format(arg))
time.sleep(arg)
def loop_through_moves():
while True:
move_mouse(1)
move_mouse(2)
move_mouse(3)
t = threading.Thread(target=loop_through_moves)
t.daemon = True
t.start()
while True:
if keyboard. is_pressed('b'):
break