Can I use Python to capture keyboard and mouse events in OSX?

Andrey Fedorov picture Andrey Fedorov · Mar 26, 2012 · Viewed 8.7k times · Source

I'm trying to write a simple macro recorder in Python for OSX - something which can capture mouse and key events as the script runs in the background and replay them. I can use autopy for the latter, is there a similarly simple library for the former?

Answer

synthesizerpatel picture synthesizerpatel · Aug 4, 2012

I ran across a few solutions to this problem today and figured I'd circle back around and share here so others could save the search time.

A nifty cross platform solution for simulating keyboard and mouse input: http://www.autopy.org/

I also found a brief but working (As of Mountain Lion) example of how to globally log key strokes. The only caveat is that you have to use Python2.6 as 2.7 doesn't seem to have the objc modules available.

#!/usr/bin/python2.6

"""PyObjC keylogger for Python
by  ljos https://github.com/ljos
"""

from Cocoa import *
import time
from Foundation import *
from PyObjCTools import AppHelper

class AppDelegate(NSObject):
    def applicationDidFinishLaunching_(self, aNotification):
        NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, handler)

def handler(event):
    NSLog(u"%@", event)

def main():
    app = NSApplication.sharedApplication()
    delegate = AppDelegate.alloc().init()
    NSApp().setDelegate_(delegate)
    AppHelper.runEventLoop()

if __name__ == '__main__':
   main()

For mouse input, simply replace NSKeyDownMask with the relevant mask from the list available here: http://developer.apple.com/library/mac/#documentation/cocoa/Reference/ApplicationKit/Classes/NSEvent_Class/Reference/Reference.html#//apple_ref/occ/clm/NSEvent/addGlobalMonitorForEventsMatchingMask:handler:

For example, NSMouseMovedMask works for tracking mouse movements. From there, you can access event.locationInWindow() or other attributes.