PyAutoGUI
PyAutoGUI is a cross-platform Python library for GUI automation, enabling programmatic control of the mouse and keyboard, and other GUI tasks like screenshots and image recognition. It simplifies complex operating system interactions into a straightforward API. Currently at version 0.9.54, the library is actively maintained with updates released periodically.
Warnings
- gotcha PyAutoGUI includes a fail-safe feature. Moving the mouse cursor to any of the four corners of the primary monitor will immediately raise a `pyautogui.FailSafeException` to stop runaway scripts. This feature is enabled by default and highly recommended to keep on.
- breaking Platform-specific dependencies are often required but not automatically installed by `pip` on macOS or Linux. Missing these can prevent core features (like screenshots or keyboard control) from working.
- gotcha The `pyautogui.typewrite()` function may not correctly handle non-US keyboard layouts or special characters/symbols, often producing incorrect input or failing for Unicode strings.
- gotcha PyAutoGUI may not function reliably inside virtual machines (VMs), sometimes controlling the host machine instead of the guest OS. This can lead to scripts executing without visible actions within the VM.
- gotcha PyAutoGUI reliably operates only on the primary monitor. Its behavior with secondary or multiple monitor setups can be inconsistent, with mouse functions potentially failing or targeting the wrong screen depending on the operating system and its version.
Install
-
pip install pyautogui -
pip3 install pyautogui
Imports
- pyautogui
import pyautogui
Quickstart
import pyautogui
import time
# Get screen size
screenWidth, screenHeight = pyautogui.size()
print(f"Screen size: {screenWidth}x{screenHeight}")
# Move mouse to center of screen
pyautogui.moveTo(screenWidth / 2, screenHeight / 2, duration=1)
# Click at current position
pyautogui.click()
# Type a message (simulates keyboard input)
pyautogui.write('Hello, PyAutoGUI!', interval=0.1)
# Press a hotkey combination (e.g., Ctrl+S to save)
# pyautogui.hotkey('ctrl', 's')
# Display an alert box
pyautogui.alert('Automation script finished!\nClick OK to exit.')