AppleScript

The AppleScript service runs scripts in the runtime and returns their results as Python values. Access it via app.applescript. It is the way to control other apps that have a scripting dictionary, such as Music, Finder, Mail or Safari.

track = app.applescript.run('''
    tell application "Music"
        if player state is not playing then return missing value
        return {title:name of current track, artist:artist of current track}
    end tell
''')
# {"title": "Blue in Green", "artist": "Miles Davis"}, or None

applescript

import nib

# Standard Additions only: no Automation permission needed.
VOLUME = """
on get_volume()
    return output volume of (get volume settings)
end get_volume

on set_volume(level)
    set volume output volume level
end set_volume
"""


def main(app: nib.App):
    app.title = "Volume"
    app.icon = nib.SFSymbol("speaker.wave.2.fill")
    app.width = 300

    system = nib.Text("", foreground_color=nib.Color.SECONDARY)
    label = nib.Text("", font=nib.Font.HEADLINE)

    def show(level):
        label.content = f"Output volume {int(level)}%"

    def change(level):
        app.applescript.call(VOLUME, "set_volume", int(level))
        show(level)

    slider = nib.Slider(value=0, min_value=0, max_value=100, on_change=change)

    def refresh():
        version = app.applescript.run("system version of (system info)")
        system.content = f"macOS {version}"
        slider.value = app.applescript.call(VOLUME, "get_volume")
        show(slider.value)

    app.on_appear = refresh

    app.build(
        nib.VStack(
            controls=[system, label, slider],
            spacing=10,
            padding=20,
            alignment=nib.HorizontalAlignment.LEADING,
        )
    )


nib.run(main)

Methods

run(source, timeout=30.0)

Run a script and return its result.

app.applescript.run(source: str, timeout: float = 30.0) -> Any
Parameter Type Description
source str The AppleScript source
timeout float Seconds to wait for the result

call(source, handler, *args, timeout=30.0)

Call a handler defined in a script. The arguments travel as AppleScript values, not as text inside the source, so quotes and other characters in them need no escaping.

app.applescript.call(source: str, handler: str, *args, timeout: float = 30.0) -> Any
Parameter Type Description
source str The AppleScript source that defines the handler
handler str The handler name, as in on set_volume(n)
*args str, int, float, bool, None, and lists and dicts of those. A dict becomes a record
timeout float Seconds to wait for the result

An argument of any other type raises TypeError before anything is sent.

SCRIPT = '''
on reveal(target)
    tell application "Finder"
        reveal POSIX file target
        activate
    end tell
end reveal
'''

app.applescript.call(SCRIPT, "reveal", '/Users/me/Desktop/the "new" folder')

Both methods block until the script finishes, like the other services. Call them from a handler or a background thread, not from code that must return immediately.

Results

AppleScript Python
text str
integer int
real float
boolean bool
missing value None
list list
record dict
file, alias str, the POSIX path
date str, ISO 8601 with the local offset
constant, such as playing str, its four-character code

Record keys that are AppleScript terms are stored as codes. name, id, class and index are translated back; other terms arrive as their code, for example pnam. Give records your own keys, {title:name of current track}, and write player state as text to get a constant's name.

Errors

Exception When
nib.AppleScriptPermissionError The app may not control the target app (error -1743 or -1744)
nib.AppleScriptError The script did not compile, or it raised an error while running
nib.ServiceTimeoutError No result within timeout

Both exceptions carry number and message. A script's own error "nope" number 1234 arrives as number == 1234.

try:
    unread = app.applescript.run('tell application "Mail" to unread count of inbox')
except nib.AppleScriptPermissionError:
    status.content = "Allow automation in System Settings > Privacy & Security"
except nib.AppleScriptError as e:
    status.content = f"Error {e.number}: {e.message}"

Permissions

Controlling another app needs the user's consent. macOS asks the first time a script sends that app an event, and the answer is kept in System Settings > Privacy & Security > Automation. Under nib run the request names the terminal or editor that started the app; in a built app it names the app.

A built app also needs NSAppleEventsUsageDescription, or the events fail with -1743 without macOS ever asking. nib build adds a generic description when the code calls app.applescript.run or call; set your own under apple_events in [tool.nib.build.plist.usage].

Standard Additions, such as set volume, get volume settings or system info, need no consent.

Notes

  • The runtime compiles a script once and keeps it, so running the same source again is cheap. A compiled script keeps its property values between calls.
  • Scripts run one at a time. A script that outlasts timeout keeps running in the runtime until it finishes; wrap calls to slow apps in with timeout of 10 seconds ... end timeout.
  • JavaScript for Automation and .scpt files are not supported.