write simple python script that moves mouse until key keybord is pressed
Assistant
Certainly! Below is a simple Python script that moves the mouse continuously until a keyboard key is pressed. It uses the pyautogui module to move the mouse and the keyboard module to detect key presses.
First, make sure you have the required modules installed:
pip install pyautogui keyboard
Here is the script:
import pyautogui
import keyboard
import time
print("Moving mouse... Press any key to stop.")
try:
while True:
# Move the mouse slightly right and then left
x, y = pyautogui.position()
pyautogui.moveTo(x + 10, y)
time.sleep(0.1)
pyautogui.moveTo(x, y)
time.sleep(0.1)
# Check if any key is pressed
if keyboard.is_pressed():
print("Key pressed, stopping.")
break
except KeyboardInterrupt:
print("Program interrupted.")
How it works:
The script moves the mouse 10 pixels to the right and then back to the original position repeatedly.
It checks continuously if any key is pressed using keyboard.is_pressed().
Ah, I see! The keyboard.is_pressed() function requires a specific key name as an argument; it doesn't detect any keypress without specifying which key to check.
To detect any key press, you can use keyboard.read_event() in a non-blocking way or set up an event hook for the first keypress.
Here's a modified approach using keyboard's event listener to stop the mouse moving as soon as any key is pressed:
import pyautogui
import keyboard
import time
print("Moving mouse... Press any key to stop.")
# Flag to control the loop
stop_moving = False
# Define a callback for any key press
def on_key(event):
global stop_moving
stop_moving = True
# Hook to listen to all keyboard events
keyboard.hook(on_key)
try:
while not stop_moving:
x, y = pyautogui.position()
pyautogui.moveTo(x + 10, y)
time.sleep(0.1)
pyautogui.moveTo(x, y)
time.sleep(0.1)
finally:
keyboard.unhook_all()
print("Key pressed, stopping.")
User
set spacebar as hotkey
Assistant
Sure! To stop the mouse movement when the spacebar is pressed, you can modify the callback to check for the specific key.
Here is the updated script that moves the mouse until you press the spacebar:
import pyautogui
import keyboard
import time
print("Moving mouse... Press SPACEBAR to stop.")
stop_moving = False
def on_key(event):
global stop_moving
# Check if the event is a key-down event and the key is space
if event.event_type == keyboard.KEY_DOWN and event.name == 'space':
stop_moving = True
keyboard.hook(on_key)
try:
while not stop_moving:
x, y = pyautogui.position()
pyautogui.moveTo(x + 10, y)
time.sleep(0.1)
pyautogui.moveTo(x, y)
time.sleep(0.1)
finally:
keyboard.unhook_all()
print("SPACEBAR pressed, stopping.")
How it works:
The on_key function checks if the event corresponds to the spacebar being pressed down.
When the spacebar is detected, it sets the flag stop_moving to True.
The main loop runs until stop_moving becomes True.
User
Modify this script
import pyautogui
import keyboard
import time
from random import randint
print("Moving mouse... Press any key to stop.")
try:
while True:
random_move = randint(1,100)
x, y = pyautogui.position()
pyautogui.moveTo(x + random_move, y)
random_time_next_move = randint(2,10)
time.sleep(random_time_next_move)
pyautogui.moveTo(x, y + random_move)
random_time_next_move = randint(4,15)
time.sleep(0.1)
if keyboard.is_pressed(hotkey='space'):
print("Key pressed, stopping.")
break
To modify your script so that it stops moving the mouse when spacebar is pressed and avoid the keyboard.is_pressed() error (which requires a key argument without keyword syntax), and also to prevent your PC from locking, you can do two things:
User
FailSafeException: PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen. To disable this fail-safe, set pyautogui.FAILSAFE to False. DISABLING FAIL-SAFE IS NOT RECOMMENDED.
Assistant
The FailSafeException is raised by PyAutoGUI when the mouse cursor moves to the upper-left corner of the screen (0,0). By default, this feature is enabled to provide an emergency stop if your script misbehaves.
User
implement
Avoid moving the mouse to corners:
Assistant
Certainly! Below is a complete Python script that moves the mouse in small random increments, ensuring it never moves into the corners (within 10 pixels of screen edges) to avoid triggering PyAutoGUI's fail-safe. The script stops when you press the spacebar.
import pyautogui
import keyboard
import time
from random import randint
print("Moving mouse... Press SPACEBAR to stop.")
# Keep fail-safe enabled
pyautogui.FAILSAFE = True
# Get screen size
screen_width, screen_height = pyautogui.size()
# Margin around edges to avoid (in pixels)
margin = 10
try:
while True:
x, y = pyautogui.position()
# Generate random small offsets
offset_x = randint(-5, 5)
offset_y = randint(-5, 5)
# Calculate new positions
new_x = x + offset_x
new_y = y + offset_y
# Clamp to avoid corners and edges
new_x = max(margin, min(screen_width - margin, new_x))
new_y = max(margin, min(screen_height - margin, new_y))
# Move mouse smoothly to new position
pyautogui.moveTo(new_x, new_y, duration=0.1)
# Wait for a small random time between moves
wait_time = randint(1, 3)
time.sleep(wait_time)
# Stop if spacebar is pressed
if keyboard.is_pressed('space'):
print("SPACEBAR pressed, stopping.")
break
except pyautogui.FailSafeException:
print("Fail-safe triggered. Exiting.")
except KeyboardInterrupt:
print("Program interrupted.")
User
Moving mouse... Press SPACEBAR to stop.
Fail-safe triggered. Exiting.
Assistant
The fail-safe is still triggering, which means the mouse is reaching the corner (or edge) despite the clamping.
When a key press is detected, it breaks the loop and stops moving the mouse.
Let me know if you want it working with specific keys or modifications!
Explanation:
keyboard.hook(on_key) listens to all keyboard events and calls on_key whenever any key event occurs.
Once any key event is detected, the flag stop_moving is set to True, which breaks the loop.
The script unregisters the keyboard hooks and prints a stop message.
Try running this script and it should work as expected!
Let me know if you want it to stop on a different key or with other behavior!
Fix the keyboard.is_pressed() usage: The function takes the key name as a positional argument, without hotkey=.
Avoid locking: Rapid and large mouse movements might trigger your PC's lock (Windows often locks after inactivity, but sometimes very repetitive input may cause issues). To reduce this:
Move the mouse in smaller random increments very frequently rather than large jumps.
Alternatively, add a small jitter or move slightly so the system thinks it's active without making large jumps.
Here is a modified version:
import pyautogui
import keyboard
import time
from random import randint
print("Moving mouse... Press SPACEBAR to stop.")
try:
while True:
# Get current mouse position
x, y = pyautogui.position()
# Move mouse by a small random offset to avoid large jumps
offset_x = randint(-5, 5)
offset_y = randint(-5, 5)
new_x = x + offset_x
new_y = y + offset_y
pyautogui.moveTo(new_x, new_y, duration=0.1) # Move smoothly
# Wait a short random time before next move
wait_time = randint(1, 3)
time.sleep(wait_time)
# Detect if spacebar is pressed to stop
if keyboard.is_pressed('space'):
print("SPACEBAR pressed, stopping.")
break
except KeyboardInterrupt:
print("Program interrupted.")
Key changes:
Moved by small offsets (±5 pixels) instead of large jumps.
Removed the incorrectly used hotkey= parameter — just 'space' in keyboard.is_pressed('space').
Added a smooth move duration to make cursor movement less abrupt.
Random wait time is short so mouse keeps active consistently but gently.
Optional tip for Windows users to prevent locking:
If you still face PC locking issues, consider adjusting your Windows power and sleep settings, or use a dedicated "keep awake" tool like caffeine or similar.
Let me know if you want the script to use event hooks or improve in any other way!
If your random mouse moves cause the cursor to reach that corner, the fail-safe triggers and aborts the program.
How to handle it:
You have two options:
Avoid moving the mouse to corners:
Restrict the mouse movement to a safe range inside the screen dimensions. For example, do not allow the mouse to move within 10 pixels of any screen edge.
Disable FailSafe (not recommended):
You can disable it by setting pyautogui.FAILSAFE = False at the beginning of your script. But this disables the emergency stop, which can be risky.
Suggestion: Restrict movement inside the screen safe bounds
Here is how you can modify your script to prevent moving mouse to corners:
import pyautogui
import keyboard
import time
from random import randint
pyautogui.FAILSAFE = True # Keep fail-safe enabled
print("Moving mouse... Press SPACEBAR to stop.")
screenWidth, screenHeight = pyautogui.size()
try:
while True:
x, y = pyautogui.position()
offset_x = randint(-5, 5)
offset_y = randint(-5, 5)
# Calculate new positions
new_x = x + offset_x
new_y = y + offset_y
# Keep mouse inside a margin (e.g., 10 pixels away from screen edges)
margin = 10
new_x = max(margin, min(screenWidth - margin, new_x))
new_y = max(margin, min(screenHeight - margin, new_y))
pyautogui.moveTo(new_x, new_y, duration=0.1)
wait_time = randint(1, 3)
time.sleep(wait_time)
if keyboard.is_pressed('space'):
print("SPACEBAR pressed, stopping.")
break
except pyautogui.FailSafeException:
print("Fail-safe triggered. Exiting.")
except KeyboardInterrupt:
print("Program interrupted.")
Notes:
We keep pyautogui.FAILSAFE = True to keep protection enabled.
We clamp the new mouse position inside the screen with a safe margin of 10 pixels to avoid corners.
This prevents accidentally triggering the fail-safe.
If you're absolutely certain you want to disable FailSafe, add at the very top:
import pyautogui
pyautogui.FAILSAFE = False
But please be careful as moving mouse to corner won't stop the script anymore.
Let me know if you want me to help add any other features or improvements!
What this does:
Moves the mouse by small steps randomly between -5 to +5 pixels in both X and Y.
Keeps the mouse position at least 10 pixels inside the screen edges, so it never touches corners.
Uses pyautogui.FAILSAFE which triggers if the mouse is moved to the upper-left corner (0,0) — but with the margin, this should never happen.
Stops on pressing the spacebar.
Smooth movement (duration=0.1) avoids abrupt jumps.
Feel free to test this and ask if you want it modified or extended!
This can happen due to:
Initial mouse position being already on or very close to the corner.
Timing issues or rounding errors.
Unexpected movement outside bounds.
Improvements to avoid FailSafe triggering:
At script start, move the mouse to a safe position inside the screen away from corners.
This prevents starting at a corner (which immediately triggers fail-safe).
Increase margin from 10 to something bigger (like 20 or 30) for extra safety.
Optional: Print each mouse position during the loop for debugging.
Here is a safer version with these fixes:
import pyautogui
import keyboard
import time
from random import randint
print("Moving mouse... Press SPACEBAR to stop.")
pyautogui.FAILSAFE = True
screen_width, screen_height = pyautogui.size()
margin = 30 # increase margin to be safe
# Move mouse initially to center of the screen (a safe spot, well away from corners)
safe_x = screen_width // 2
safe_y = screen_height // 2
pyautogui.moveTo(safe_x, safe_y, duration=0.5)
try:
while True:
x, y = pyautogui.position()
offset_x = randint(-5, 5)
offset_y = randint(-5, 5)
new_x = x + offset_x
new_y = y + offset_y
# Clamp inside the area away from edges
new_x = max(margin, min(screen_width - margin, new_x))
new_y = max(margin, min(screen_height - margin, new_y))
# Debug print position (optional)
#print(f"Moving mouse to: {new_x}, {new_y}")
pyautogui.moveTo(new_x, new_y, duration=0.1)
wait_time = randint(1, 3)
time.sleep(wait_time)
if keyboard.is_pressed('space'):
print("SPACEBAR pressed, stopping.")
break
except pyautogui.FailSafeException:
print("Fail-safe triggered. Exiting.")
except KeyboardInterrupt:
print("Program interrupted.")
Try this version. Moving the mouse initially to screen center and increasing the margin very strongly reduces the chance of hitting the fail-safe.
If it still triggers, consider:
Whether you have multiple monitors with different coordinates (in which case, screen coordinates can include negatives, and clamp logic should be adjusted).
Or if something else moves your mouse.
If you have multiple monitors or virtual desktops, let me know — I can help adjust for that too.