Random ramblings about Mac, Python, TeX, programming, and more   |     |        |     |  



MacOS automation with Python and AppleScript

February 21, 2020  |  programming, macos

I prefer to program in Python, but for automation on the Mac, AppleScript is still a great tool. Especially paired with a good AppleScript editor/debugger like Script Debugger. For many projects, it would be nice to do most of the scripting in Python and only do the interaction with the different programs (GUI) in AppleScript. The obvious solution is PyObjC and its ScriptingBridge framework (wrapper for the ScriptingBridge framework of macOS). However, to make it easier for us, Raymond Yee has created py-applescript, an easy-to-use Python wrapper for NSAppleScript (allowing Python scripts to communicate with AppleScripts and AppleScriptable applications). I use pip to install it (pip3.8 to ensure it is installed for Python 3.8):

pip3.8 install py-applescript

If we take the Microsoft Outlook download pictures AppleScript code in this previous post, I can insert it into an AppleScript function downloadpictures resulting in the following code:

on downloadpictures()

  tell application "System Events" to tell process "Microsoft Outlook"
    set frontmost to true

    -- Position and width
    set {x, y} to position of window 1
    set {w, h} to size of window 1

    -- Approx position of button "Download pictures"
    click at {x + w - 60, y + 255}

  end tell

end download pictures

If I save this AppleScript code in the Download-Pictures.applescript file, I can, with py-applescript and PyObjC installed, call the AppleScript function downloadpictures from Python like this:

import applescript
scpt = applescript.AppleScript(path="Add-Rules-To-Outlook.applescript")
scpt.call("downloadpictures")
Last updated: June 22, 2024