tags:

views:

1163

answers:

4

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.

Thanks!

+5  A: 

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,
                                        kCGMouseButtonCenter);
    //Apparently, a bug in xcode requires this next line
    CGEventSetType(eventRef, kCGEventMouseMoved);
    CGEventPost(kCGSessionEventTap, eventRef);
    CFRelease(eventRef);

    return 0;
}

Now to write Python bindings!

Ben
Maybe try ctypes instead of bindings?
technomalogical
+3  A: 

When I wanted to do it, I installed Jython and used the java.awt.Robot class. If you need to make a CPython script this is obviously not suitable, but for projects where you the flexibility to choose anything, it is a nice cross-platform solution.

Jeremy Banks
A: 

The easiest way? Compile this Cocoa app and pass it your mouse movements.

Another way? Import pyobjc to access some of the OSX framework and access the mouse that way. (see the code from the first example for ideas).

Rizwan Kassim
+1  A: 

Just try this code:

#!/usr/bin/python

import objc

class ETMouse():    
    def setMousePosition(self, x, y):
        bndl = objc.loadBundle('CoreGraphics', globals(), 
                '/System/Library/Frameworks/ApplicationServices.framework')
        objc.loadBundleFunctions(bndl, globals(), 
                [('CGWarpMouseCursorPosition', 'v{CGPoint=ff}')])
        CGWarpMouseCursorPosition((x, y))

if __name__ == "__main__":
    et = ETMouse()
    et.setMousePosition(200, 200)

it works in OSX leopard 10.5.6