Press key with Python on OS X

22 May 2011

This is what I had to do to programmatically generate key pressed and mouse events on OS X with Python.
First I had to download a Python wrapper around Objective C which I found here. I downloaded the trunk (with svn) and then I navigated to the folder containing Quartz and ran the setup script.

	$	svn checkout
	$	cd trunk/pyobjc/pyobjc-framework-Quartz 
	$	python install

Checking out the trunk acctualy checks out a lot of files not not needed, but hey, better safe than sorry.
After this was done I was able to import the Quart.CoreGraphics module in python.
I borrowed this code snippet from here to make sure it worked, and it did, like a charm.
	import sys
	import os
	import time
	from Quartz.CoreGraphics import CGEventCreateMouseEvent
	from Quartz.CoreGraphics import CGEventPost
	from Quartz.CoreGraphics import kCGEventMouseMoved
	from Quartz.CoreGraphics import kCGEventLeftMouseDown
	from Quartz.CoreGraphics import kCGEventLeftMouseDown
	from Quartz.CoreGraphics import kCGEventLeftMouseUp
	from Quartz.CoreGraphics import kCGMouseButtonLeft
	from Quartz.CoreGraphics import kCGHIDEventTap
	def mouseEvent(type, posx, posy):
	        theEvent = CGEventCreateMouseEvent(None, type, (posx,posy), kCGMouseButtonLeft)
	        CGEventPost(kCGHIDEventTap, theEvent)
	def mousemove(posx,posy):
	        mouseEvent(kCGEventMouseMoved, posx,posy)
	def mouseclick(posx,posy):
	        mouseEvent(kCGEventLeftMouseDown, posx,posy)
	        mouseEvent(kCGEventLeftMouseUp, posx,posy)
	def main():
	if __name__ == '__main__':

Read more on how to use Quartz here

blog comments powered by Disqus