Ben Ben - 1 year ago 79
Python Question

Controlling the mouse from Python in OS X

What would be the easiest way to move the mouse around (and possibly click) using python on OS X?

This is just for rapid prototyping, it doesn't have to be elegant.


Ben Ben
Answer Source

I dug through the source code of Synergy to find the call that generates mouse events:

#include <ApplicationServices/ApplicationServices.h>

int to(int x, int y)
    CGPoint newloc;
    CGEventRef eventRef;
    newloc.x = x;
    newloc.y = y;

    eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc,
    //Apparently, a bug in xcode requires this next line
    CGEventSetType(eventRef, kCGEventMouseMoved);
    CGEventPost(kCGSessionEventTap, eventRef);

    return 0;

Now to write Python bindings!