Control the Mouse on Mac with Python: PyAutoGUI in Practice

If you have ever wished you could make the cursor do the boring parts of a task for you — clicking through the same four dialogs, dragging files into the same folder, walking a client through a UI demo for the tenth time — then driving the mouse from Python is the skill you want. On a Mac it is genuinely easy once two things are right: the library call you make, and the privacy permission macOS demands in return.

This guide shows you how to control the mouse on Mac using Python, from a clean install through the full pointer API, macOS permission handling, image-based clicking, a complete working script, and the troubleshooting steps that save hours when something silently fails. Everything here reflects current stable releases in 2026 and the current macOS System Settings interface.

Table of Contents#

  1. What Mouse Control on a Mac Actually Involves
  2. Prerequisites: A Current Python on macOS
  3. Install PyAutoGUI on macOS
  4. Grant the macOS Privacy Permissions
  5. Your First Mouse Script on Mac
  6. The Mouse API You Will Use Every Day
  7. Timing and Safety: FAILSAFE, PAUSE, and macOS Delays
  8. Clicking What You Can See: Screenshots and Image Matching
  9. Practical Example: A Repeatable Safari Walkthrough
  10. Other Ways to Control the Mouse on Mac
  11. Troubleshooting Common Problems
  12. Best Practices and Common Mistakes
  13. Conclusion
  14. References

What Mouse Control on a Mac Actually Involves#

When a Python script "moves the mouse," it is not sending a USB packet to your trackpad. It synthesizes pointer events and hands them to the macOS window server, exactly as if a human had produced them. Applications on screen respond normally: buttons highlight, drags reorder lists, scroll wheels move pages.

Three consequences follow from that design:

  • Your script needs permission. macOS protects users from software that quietly takes over the pointer, so an app must be trusted under Privacy & Security before its events are accepted. This is the number one reason a first script appears to run but nothing moves.
  • Your script needs to be well behaved. Once trusted, the script can do anything a human can with a pointer. A bad coordinate or a runaway loop can click "Delete" for you, so you want built-in kill switches.
  • Coordinates are screen coordinates. PyAutoGUI uses a plain Cartesian system: (0, 0) is the top-left corner of the primary display, x grows to the right, and y grows downward. The bottom-right pixel of a 1920 x 1080 screen is (1919, 1079), not (1920, 1080).

Typical uses include GUI smoke tests and regression checks, prototyping automation before investing in a proper test framework, repetitive desktop chores, demo and training bots, and accessibility helpers that drive third-party apps you cannot modify.

Prerequisites: A Current Python on macOS#

Grab a current Python 3 before anything else. As of October 2026, Python 3.15.0 is the newest stable release, with 3.14.x still receiving maintenance updates.

python3 --version

Two things worth knowing about Python on a Mac:

  1. /usr/bin/python3 is not really yours. Recent macOS versions ship a python3 that belongs to the Xcode Command Line Tools. It is older and incomplete, Apple controls it, and the Python documentation explicitly says never to modify or delete it. Use it only as a last resort for one-off system scripts.
  2. Install a proper interpreter. The Python Software Foundation publishes universal2 installers on python.org that run natively on Apple Silicon and Intel Macs, and Homebrew is a fine alternative. Either way, the installer's own python3 should shadow the system one on your PATH.

Create a virtual environment for the project so the automation stack stays isolated from everything else:

mkdir mac-mouse-demo && cd mac-mouse-demo
python3 -m venv .venv
source .venv/bin/activate
python3 --version

Install PyAutoGUI on macOS#

The most productive starting point for mouse control in Python is PyAutoGUI — a small, cross-platform GUI automation library that wraps the native Cocoa and Quartz APIs on macOS behind a readable function-call interface. Its current stable release is 0.9.54.

Install it the way the project documents for macOS:

python3 -m pip install --upgrade pip
python3 -m pip install pyautogui

You do not need a separate pip install pyobjc step. On macOS, the package pulls in pyobjc-core and pyobjc-framework-quartz automatically, plus its own support modules: Pillow for image work, PyScreeze for screenshots, PyGetWindow, PyMsgBox, PyTweening, and MouseInfo. The current PyObjC releases support Python 3.10 through 3.15 and run natively on Apple Silicon and Intel.

Verify the install from the interpreter:

import pyautogui
 
width, height = pyautogui.size()
print(f"Primary display: {width} x {height}")
print("Pointer at:", pyautogui.position())

If you later want fuzzy image matching via confidence=..., add OpenCV as an optional extra (python3 -m pip install opencv-python).

Grant the macOS Privacy Permissions#

This is the step that trips up almost everyone, and it is the one older write-ups describe wrongly. macOS does not care which package you installed; it cares which application is driving the pointer — Terminal, iTerm2, VS Code, PyCharm, or a bundled .app that launches your interpreter. Trust is granted to that app.

Apple splits the relevant permissions across three panes of System Settings > Privacy & Security (older guides call this "System Preferences > Security & Privacy"; the current interface is System Settings):

PermissionNeeded forWhat it covers
AccessibilityMoving, clicking, dragging, typingLetting an app control your Mac
Input MonitoringListening to mouse, trackpad, or keyboard eventsLetting an app observe input system-wide
Screen & System Audio Recordingscreenshot() and locateOnScreen()Letting an app capture what is on screen

1. Accessibility — required to drive the pointer#

  1. Open Apple menu > System Settings > Privacy & Security > Accessibility.
  2. If your terminal or editor is listed, turn its switch on. If it is not listed, click the plus button at the bottom of the app list, navigate to it, and add it.
  3. Fully quit and reopen that application. Permissions of this kind are read when the process starts, so a running session will keep failing until you relaunch it.

You should see the same guidance in Apple's own user guide: when a third-party app wants accessibility control, macOS alerts you and you must explicitly allow it in Privacy & Security settings. Grant access only to apps you trust.

2. Input Monitoring — required to watch events#

If your project also listens to the pointer (event hooks, record-and-replay tools such as macmouse, or a pynput listener), add the same app under Input Monitoring as well. Without it you get a clear warning that starts This process is not trusted! Input event monitoring will not be possible...

3. Screen & System Audio Recording — required for screenshots#

Screen capture on macOS goes through Pillow's ImageGrab in current PyScreeze builds (older Pillow versions fall back to the built-in screencapture command). Either way, macOS gates screen capture behind Screen & System Audio Recording, so add your terminal or IDE there too. Symptom if you skip it: black or empty captures.

A quick smoke test for permissions#

Run this before writing anything complex:

import pyautogui
 
pyautogui.FAILSAFE = True
pyautogui.moveTo(200, 200, duration=0.4)
pyautogui.move(60, 40, duration=0.4)
print("Cursor is now at:", pyautogui.position())

If the cursor visibly moves, Accessibility is granted. If nothing happens and no exception is raised, the permission is almost certainly attached to a different app than the one running the interpreter.

Your First Mouse Script on Mac#

With permissions in place, a minimal script is short. Read the screen size first so you never aim outside the display:

import pyautogui
 
screen_width, screen_height = pyautogui.size()
 
# Move to the center of the screen over one second
pyautogui.moveTo(screen_width // 2, screen_height // 2, duration=1)
 
# Left-click where the cursor now sits
pyautogui.click()
print("Pointer:", pyautogui.position())

Two helper calls are worth internalizing right away:

  • pyautogui.position() returns the current pointer location and is the fastest way to discover the coordinates of any on-screen target. Park the pointer over a button and print the position.
  • pyautogui.mouseInfo() opens a small inspector window that shows live coordinates and pixel colors, so you can survey a screen once and then write the script. It saves a lot of guesswork.

The Mouse API You Will Use Every Day#

Coordinates and screen queries#

CallReturnsNotes
pyautogui.size()(width, height) of the primary displayBounds of valid coordinates
pyautogui.position()(x, y) of the cursorDoes not trigger the fail-safe check
pyautogui.onScreen(x, y)True / FalseFalse for x == width or y == height

Moving the cursor#

moveTo(x, y, duration=0, tween=...) moves to absolute coordinates. Passing None for x or y keeps that axis unchanged, which is handy for axis-constrained moves.

pyautogui.moveTo(100, 200)             # instantly
pyautogui.moveTo(100, 200, duration=2) # over two seconds
pyautogui.moveTo(None, 500)            # same x, new y

Relative movement uses move(dx, dy, duration=0, tween=...) — also available as the older alias moveRel():

pyautogui.move(100, 50, duration=0.5)   # 100 right, 50 down
pyautogui.move(-30, 0)                  # 30 left

Any duration below MINIMUM_DURATION (0.1 seconds by default) is treated as instant. For more natural motion, pass an easing function as the tween argument, for example pyautogui.moveTo(x, y, duration=1.5, tween=pyautogui.easeOutQuad). Available tweens include easeInQuad, easeOutQuad, easeInOutQuad, easeInBounce, and easeInElastic.

Clicking#

click() accepts both positioning and repetition in a single call:

pyautogui.click()                                   # left click in place
pyautogui.click(200, 220)                           # move, then click
pyautogui.click(button="right")                     # right click
pyautogui.click(clicks=2, interval=0.15)            # double click
pyautogui.click(x=200, y=220, clicks=3, interval=0.1)

The button argument accepts "left", "middle", "right", and the OS-aware "primary" / "secondary" (which respect a swapped-button setup). For readability, dedicated helpers exist too: leftClick(), rightClick(), middleClick(), doubleClick(), and tripleClick(). All of them accept optional x, y, interval, and duration arguments.

A small detail that matters on macOS: apps decide what counts as a double-click from the timing between two clicks. Use doubleClick() (or click(clicks=2, interval=0.15)) so the pair is issued in one call; two manual mouseDown()/mouseUp() sequences with a long gap in between are treated as two separate single clicks.

Scrolling#

scroll(clicks, x=None, y=None) scrolls vertically, where positive values scroll up and negative values scroll down. The clicks unit is one notch of the scroll wheel. Pass x and y to scroll at a specific point rather than the current cursor position.

pyautogui.scroll(-5)     # five notches down
pyautogui.scroll(3, x=800, y=400)

For sideways scrolling use hscroll(clicks); vscroll(clicks) is the vertical equivalent of scroll().

Dragging#

dragTo(x, y, duration, button="left") drags to an absolute point, drag(dx, dy, ...) (alias dragRel()) drags relative to the current position. Both press the button, move, and release.

pyautogui.dragTo(600, 450, duration=0.8, button="left")
pyautogui.drag(0, 180, duration=0.6)

macOS-specific: a drag cannot complete instantly on a Mac. Always pass a non-zero duration, otherwise the press, move, and release collapse into the same instant and nothing on screen gets dragged.

Fine-grained control with mouseDown() and mouseUp()#

For drawing, marquee selection, or any hold-and-move gesture, split the button events apart:

start_x, start_y = 260, 220
side = 160
 
pyautogui.moveTo(start_x, start_y, duration=0.4)
pyautogui.mouseDown(button="left")
try:
    pyautogui.move(side, 0, duration=0.4)
    pyautogui.move(0, side, duration=0.4)
    pyautogui.move(-side, 0, duration=0.4)
    pyautogui.move(0, -side, duration=0.4)
finally:
    pyautogui.mouseUp(button="left")

The try/finally block is deliberate: if an exception escapes while the button is held, the pointer is left in a pressed state and the rest of your session behaves strangely.

Timing and Safety: FAILSAFE, PAUSE, and macOS Delays#

An automated cursor is hard to catch by hand, so PyAutoGUI ships with three safety mechanisms you should leave enabled.

The corner fail-safe#

With pyautogui.FAILSAFE = True (the default), any call raises pyautogui.FailSafeException while the cursor is in one of the four corners of the primary monitor. Slamming the cursor into a corner is the reliable way to abort a script that has gone wrong. Keep it on unless you have a specific reason not to.

Note that this exception has nothing to do with macOS permissions. If you see FailSafeException, the pointer reached a corner; it does not mean Accessibility was denied.

PAUSE#

pyautogui.PAUSE is a delay added after every public function call, 0.1 seconds by default. Raising it is the cheapest way to slow a jumpy script down:

import pyautogui
 
pyautogui.PAUSE = 0.25
pyautogui.DARWIN_CATCH_UP_TIME = 0.02

DARWIN_CATCH_UP_TIME#

pyautogui.DARWIN_CATCH_UP_TIME is a macOS-only extra delay (0.01 seconds by default) inserted after keyboard and mouse events, because the system needs a brief moment to process them. If actions occasionally "drop" on a Mac, raising this value is the fix to reach for.

For waits that should not apply to every call, use pyautogui.sleep(1.5) (or time.sleep()), and prefer explicit waits for a UI element to appear over fixed sleeps.

Clicking What You Can See: Screenshots and Image Matching#

Hardcoded coordinates break whenever a window moves, a display changes, or a font shifts. The robust approach is to click on what you can see: capture the screen, find an image of the target, and click its center.

import pyautogui
 
im = pyautogui.screenshot()                 # Pillow Image of the whole screen
im.save("full_screen.png")
 
crop = pyautogui.screenshot(region=(0, 0, 320, 240))  # left, top, width, height
 
box = pyautogui.locateOnScreen("save_button.png")   # (left, top, width, height)
x, y = pyautogui.center(box)
pyautogui.click(x, y)
 
x, y = pyautogui.locateCenterOnScreen("save_button.png")
pyautogui.click(x, y)
 
pyautogui.click("save_button.png")          # shortcut: find and click

Details that save time later:

  • Not-found behavior. Since PyAutoGUI 0.9.41, the locate functions raise pyautogui.ImageNotFoundException when the template is not on screen, rather than returning None. Catch that exception when a missing element is an expected outcome.
  • Speed. A full-screen locate takes on the order of one to two seconds. Pass region=(left, top, width, height) to search only the area where the control can appear, add grayscale=True for a modest speedup, or install OpenCV and use confidence=0.9 to tolerate tiny pixel differences (the confidence argument requires the OpenCV bindings).
  • Pixel checks. pyautogui.pixel(x, y) returns an RGB value and pyautogui.pixelMatchesColor(x, y, (r, g, b), tolerance=10) verifies it — useful for cheap "did the dialog close?" probes.

Two Mac-specific caveats#

  1. Retina scaling. On a Retina panel, size() reports logical points (for example 1280 x 800 for a 2560 x 1600 screen) while screenshots are often captured at 2x density. When a template is matched against a 2x capture, the returned coordinates can come out doubled relative to position(), so a click lands in the wrong place. Capture templates and screenshots at the same scale, and if coordinates are exactly 2x or 0.5x what you expect, divide or multiply by the display scale factor. This mismatch is a known project issue on high-density displays.
  2. Displays. PyAutoGUI officially supports only the primary monitor; behavior on a second display is not reliable. Keep automated work on the built-in or primary screen, or script window movement first so the target lands on the primary display.

Practical Example: A Repeatable Safari Walkthrough#

The script below runs a small browser walkthrough: launch Safari at a URL, focus the page, scroll through it, and save a screenshot as evidence. It uses no magic Dock coordinates — apps are launched by name, the page is focused at screen center, and the helper is ready for image-based targets when you need them.

import subprocess
import time
import pyautogui
 
pyautogui.FAILSAFE = True
pyautogui.PAUSE = 0.15
pyautogui.DARWIN_CATCH_UP_TIME = 0.02
 
def find_and_click(image, timeout=10, region=None):
    deadline = time.time() + timeout
    while time.time() < deadline:
        try:
            x, y = pyautogui.locateCenterOnScreen(image, region=region)
        except pyautogui.ImageNotFoundException:
            pyautogui.sleep(0.25)
            continue
        pyautogui.click(x, y)
        return True
    raise TimeoutError(f"Could not find {image} on screen")
 
subprocess.run(["open", "-a", "Safari", "https://example.com"], check=True)
pyautogui.sleep(2)
 
width, height = pyautogui.size()
pyautogui.click(width // 2, height // 2, duration=0.3)
 
for _ in range(5):
    pyautogui.scroll(-3)
    pyautogui.sleep(0.3)
 
pyautogui.screenshot().save("safari_walkthrough.png")
print("Done. Screenshot saved as safari_walkthrough.png")

Run it with python3 safari_walkthrough.py and keep one hand on the trackpad: the first time through, you can still slam the cursor into a corner to abort.

How to adapt it:

  • Target a specific control — crop a small PNG of a button from a screenshot and call find_and_click("button.png", region=(0, 0, width, 300)).
  • Add keyboard input where it is faster — pyautogui.hotkey("command", "l") focuses the Safari address bar more reliably than clicking it, and pyautogui.write("https://example.org", interval=0.05) plus pyautogui.press("enter") completes navigation. Mouse and keyboard calls mix freely.
  • Drag files — mouseDown() over a file icon, move() to the target folder, mouseUp(), with mouseUp() in a finally block.
  • Clean up — save the screenshot path and any produced artifacts into a folder your test report can read.

Other Ways to Control the Mouse on Mac#

PyAutoGUI is the right default for most people, but it is not the only option.

OptionBest forNotes
PyAutoGUIOne-off scripts, rapid prototyping, GUI smoke testsSimplest API; screenshots and image matching included; primary monitor only
pynputScripts that must also watch inputController for movement/clicks/scrolling, Listener for global event hooks; listeners expose IS_TRUSTED; keyboard monitoring needs extra trust on macOS
PyObjC + Quartz eventsFull control over event flags, timing, and multi-display coordinatesCGEventCreateMouseEvent / CGEventPost under the Quartz framework; more code, same Accessibility requirement
macmouseRecord-and-replay of mouse activityEvent hooks plus playback; Accessibility permission required
cliclickShell pipelines and quick manual probingA Homebrew-installable macOS command-line tool for clicks, moves, and text entry from the terminal

Rough guidance: start with PyAutoGUI, switch to pynput the moment you need global listeners, and drop to Quartz events only when you need low-level control PyAutoGUI does not expose.

Troubleshooting Common Problems#

The script runs, prints output, but the cursor never moves. Accessibility permission is missing or attached to the wrong app. Re-check System Settings > Privacy & Security > Accessibility for the terminal or IDE that actually runs the interpreter, then fully quit and reopen it.

This process is not trusted! Input event monitoring will not be possible... The app is not in the Input Monitoring list (or Accessibility, depending on what the code does). Add it and relaunch the app.

Clicks land at twice the expected coordinates. Retina density mismatch between screenshots and coordinates. Capture templates at the same scale as your screenshots, or correct for the scale factor. Confirm with pyautogui.size() — if it reports half of what you think the panel is, you are seeing logical points.

dragTo() or drag() does nothing on my Mac. Give the drag a duration of at least a couple of tenths of a second; macOS drags cannot be instantaneous.

ImageNotFoundException on every locate call. The template does not match the live pixels: different theme, scaling, or window position. Re-crop the template from a fresh screenshot(), search a region, and consider confidence with OpenCV installed.

Screenshots come out black or are refused. Screen & System Audio Recording is not granted to the running app.

Actions drop out on a fast machine. Increase pyautogui.DARWIN_CATCH_UP_TIME and pyautogui.PAUSE, and wait for the UI to settle after opening windows.

Second-display coordinates are nonsense. Only the primary monitor is supported; move the target window to the primary display first.

A script is out of control. Slam the cursor into any screen corner to raise FailSafeException, or press Ctrl-C in the terminal. Prevent the situation by leaving FAILSAFE on and keeping PAUSE reasonable.

It works in Terminal but not from my IDE or a launch agent. The IDE (or the agent) is a separate application and needs its own permission entries. Do not assume trust is inherited.

Best Practices and Common Mistakes#

  1. Keep FAILSAFE = True. Disabling it turns a small bug into a cursor you cannot stop.
  2. Prefer anchors over magic numbers. Launch apps with open -a AppName or URL schemes instead of clicking Dock icons, use hotkey() for well-known shortcuts, and use locateOnScreen() for everything else. Reserve hardcoded coordinates for truly fixed UI.
  3. Wait for state, not for luck. Poll with a find_and_click()-style helper and a timeout instead of stacking sleep() calls and hoping the app keeps up.
  4. Release the button. Pair mouseDown() with mouseUp() in try/finally so a failure never leaves a button stuck down.
  5. Discover coordinates properly. Use pyautogui.mouseInfo() or a small position() polling loop (print(pyautogui.position()) each second) while you hover targets — and remember to import time if you add a sleep.
  6. Slow down before speeding up. Get a workflow correct with generous PAUSE, then tighten timings.
  7. Pin down your environment. Use a virtual environment, record the Python and PyAutoGUI versions in your project, and run python3 -m pip install --upgrade pyautogui when behavior on macOS changes after an OS update.
  8. Treat Accessibility as a security decision. Granting it gives that app full control of your Mac, so only automate with code you trust, and respect the terms of service of any application or site you script.
  9. Design for failure. Expect ImageNotFoundException, permission denials, and layout changes; make scripts exit with a clear message rather than clicking on.

Conclusion#

Controlling the mouse on Mac using Python comes down to a clean loop: install a current Python, add PyAutoGUI with python3 -m pip install pyautogui, grant Accessibility (plus Input Monitoring and Screen Recording when you listen or capture), then drive the pointer with moveTo(), click(), scroll(), and dragTo() while FAILSAFE and PAUSE keep you in control.

The quality difference between fragile and reliable Mac automation is rarely the library call — it is the surrounding discipline: correct permissions for the app that runs the interpreter, macOS-aware timing via DARWIN_CATCH_UP_TIME, non-zero drag durations, image-based targets instead of brittle pixels, and an escape hatch you never turn off. Master those, and the cursor becomes a dependable part of your toolchain.

References#