Python, PyObjC, ScriptingBridge and AppleScript
I’ve recently been investigating the best way to control Keynote from another application. I know it’s possible with AppleScript, but AppleScript confuses me, so I thought I would try to avoid it.
After looking around, I finally found ScriptingBridge, which is a framework developed by Apple. It can be accessed from ObjC, Ruby and Python. However, I found there was very little documentation explaining how to use it. In this post, I plan to quickly show the key points, which I have found out through Google, and trial and error.
In Python, (assuming you have PyObjC installed) you can get up and running like this:
Note: I am using Keynote 6.1.
Also note: Keynote.startSlideshow()
will not work with previous versions of Keynote.
(You can find out what functions they support as described below, using the help()
function.)
Talking to Keynote
#!/usr/bin/env python3
from Foundation import *
from ScriptingBridge import *
Keynote = SBApplication.applicationWithBundleIdentifier_("com.apple.iWork.Keynote")
if Keynote.isRunning():
Keynote.startSlideshow()
To find out what functions you have access to, you can use Python’s built in help()
function.
Supposing you have typed the above code into an interactive prompt, you can use help(Keynote)
obtain a list of all available functions.
One of the trickiest things for me was working out the Bundle identifier. I assumed it would be
com.apple.Keynote
, but it wasn’t. To find it, try looking at the names of the files in
/Library/Preferences
or ~/Library/Preferences
. For instance, I found that Keynote was
com.apple.iWork.Keynote
, and that iTunes was com.apple.iTunes
.