Cursor automation in Python can be achieved using libraries like pyautogui
, which allows you to control the mouse and keyboard, take screenshots, and perform various other automation tasks. Below are the steps to get started with pyautogui
for cursor automation:
1.Install pyautogui:
pip install pyautogui
2.Basic Usage:
import pyautogui # Move the cursor to a specific position (x, y) pyautogui.moveTo(100, 200, duration=1) # Move to (100, 200) over 1 second # Click at the current position pyautogui.click() # Right-click at the current position pyautogui.rightClick() # Double-click at the current position pyautogui.doubleClick() # Move the cursor relative to its current position pyautogui.moveRel(50, -50, duration=1) # Move 50 pixels right and 50 pixels up over 1 second # Get the current position of the cursor x, y = pyautogui.position() print(f"Current position: ({x}, {y})") # Drag the cursor to a specific position pyautogui.dragTo(300, 400, duration=2) # Drag to (300, 400) over 2 seconds # Scroll up or down pyautogui.scroll(500) # Scroll up 500 units pyautogui.scroll(-500) # Scroll down 500 units
3.Safety Measures:
To avoid running into issues where the script might go out of control, you can set up a fail-safe feature. Moving the mouse to the top-left corner of the screen will immediately stop the execution of the script.
pyautogui.FAILSAFE = True
4.Real-world Example:
Here is a script that moves the cursor in a square pattern:
import pyautogui import time pyautogui.FAILSAFE = True # Define the side length of the square side_length = 100 # Move the cursor in a square pattern for _ in range(4): pyautogui.moveRel(side_length, 0, duration=1) # Move right time.sleep(0.5) pyautogui.moveRel(0, side_length, duration=1) # Move down time.sleep(0.5) pyautogui.moveRel(-side_length, 0, duration=1) # Move left time.sleep(0.5) pyautogui.moveRel(0, -side_length, duration=1) # Move up time.sleep(0.5)
With these basics, you can automate various tasks involving mouse movements and clicks. If you have a specific task in mind, feel free to share more details, and I can help you create a more tailored script.