If the script window loses focus, some key-listening libraries (like keyboard) stop receiving events—especially on macOS or when you don’t run the script with admin/root rights.
A robust, cross-platform way is to switch to pynput, which hooks into the OS globally, so the hot-key works no matter which window is active.
Below is a fully self-contained example that:
• moves + clicks in your square pattern on an infinite loop
• stops immediately when you press the J key anywhere
• still supports PyAutoGUI’s failsafe (move mouse to a screen corner)
#!/usr/bin/env python3
import time
import threading
import pyautogui # mouse automation
from pynput import keyboard # global hot-key listener
# --------------------------------------------
# Adjustable parameters
# --------------------------------------------
DISTANCE = 100 # pixels in each direction
DURATION = 0.50 # seconds per leg of the move
START_DELAY = 3 # time to place your mouse
# --------------------------------------------
# Stop-flag that both threads can check
# --------------------------------------------
stop_event = threading.Event()
def on_press(key):
"""
Callback fired on every key press.
If 'j' or 'J' is pressed we set the stop flag.
"""
try:
if key.char and key.char.lower() == 'j':
print("\n[J] pressed — stopping loop.")
stop_event.set()
# Returning False stops the listener cleanly
return False
except AttributeError:
# Special keys (Ctrl, Alt, etc.) are ignored
pass
# Start the keyboard listener in a background thread
listener = keyboard.Listener(on_press=on_press)
listener.start()
print(f"Place your mouse at the starting position — "
f"script begins in {START_DELAY} s. (Press J any time to quit)")
time.sleep(START_DELAY)
# --------------------------------------------
# Main loop
# --------------------------------------------
try:
while not stop_event.is_set():
# 1️⃣ starting click
pyautogui.click()
# 2️⃣ down-right
pyautogui.moveRel( DISTANCE, DISTANCE, duration=DURATION)
pyautogui.click()
# 3️⃣ down-left
pyautogui.moveRel(-DISTANCE, DISTANCE, duration=DURATION)
pyautogui.click()
# 4️⃣ up-left
pyautogui.moveRel(-DISTANCE, -DISTANCE, duration=DURATION)
pyautogui.click()
# 5️⃣ up-right
pyautogui.moveRel( DISTANCE, -DISTANCE, duration=DURATION)
pyautogui.click()
except pyautogui.FailSafeException:
print("\nPyAutoGUI fail-safe triggered (mouse hit screen corner).")
finally:
# Make sure listener thread shuts down
stop_event.set()
listener.join()
print("Done. Goodbye 👋")
Installation (once):
pip install pyautogui pynput
Extra notes & troubleshooting
- macOS: The first time you run this, macOS will ask for “Input Monitoring” or “Accessibility” permission for your terminal/app. Grant it so the global key-hook works.
- Windows: Should work out of the box; no admin rights needed for
pynput.
- Linux: If you get a permission error, run the script with
sudo or ensure your user belongs to the input group.
- You still have two emergency stop options:
• Press J anywhere.
• Failsafe: move the mouse to any screen corner (PyAutoGUI raises FailSafeException).
Have fun automating! 💻🖱️