appscript

osascript

AppleScripts may be executed from the command line via the osascript command.

Usage

The osascript command accepts either a path to a compiled/uncompiled AppleScript file, or one or more individual AppleScript statements (via the -e option). Alternatively, an uncompiled AppleScript starting with #!/usr/bin/osascript and made executable may be run directly from the command line.

osascript will invoke the script's run handler, which may be implicit or explicit. If the run handler is explicitly declared, it will receive a list of zero or more argument strings as its direct parameter.

The return value (if any) may be anything. By default, it is printed in human-readable format; this may be modified using the -s option.

Use AppleScript's log command to write to stderr.

On completion, the status code will be 0 unless an error occurred. Additional error information is written to stderr.

There is no way to pass input data via stdin. Either pass all input data as arguments or write it to a temp file, then pass the path to that file and have the AppleScript read the temp file directly (e.g. read (POSIX file thePath) as «class utf8»).

Python and Ruby scripts can use osascript via the subprocess module and IO class respectively.

See man osascript for more information.

Examples

The following script adds together zero or more numeric arguments:

on run argv
    set n to 0
    repeat with argRef in argv
        set n to n + argRef
    end repeat
    return n
end run

Or, if the number of arguments is fixed, the handler may be written more compactly by using multiple assignment:

on run {a, b}
    return a + b
end run
Save the script as a compiled AppleScript file named add_to.scpt and test it as follows:
$ osascript /path/to/add_to.scpt 1 3
4

To invoke a compiled version of the same script from Python:

#!/usr/bin/python

import subprocess

scpt = '/path/to/add_to.scpt'

args = [1, 3]

p = subprocess.Popen(
        ['/usr/bin/osascript', scpt] + [str(arg) for arg in args], 
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)

out, err = p.communicate()

if p.returncode:
    print 'ERROR:', err
else:
    print int(out) # 4

Alternatively, you can pass the AppleScript source code to osascript via its stdin:

#!/usr/bin/python

import subprocess

args = [1, 3]

p = subprocess.Popen(
        ['/usr/bin/osascript', '-'] + [str(arg) for arg in args], 
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        stdin=subprocess.PIPE)

scpt = '''
on run argv
    set n to 0
    repeat with argRef in argv
        set n to n + argRef
    end repeat
    return n
end run
'''

out, err = p.communicate(scpt)

if p.returncode:
    print 'ERROR:', err
else:
    print (out) # 4

This may be slightly slower (since osascript has to compile the AppleScript every time it runs) but avoids the need to use a separate compiled AppleScript (.scpt) file.