0

Given the following AppleScript code

on myHandler()
    display dialog ("I'm your Handler!")
end myHandler

How do I call myHandler from osascript (using Terminal), plain without parameters, but also with?

3
0

Found a workaround. Not clean, but it works. In my case with Python:

import subprocess
    
with open("script.scpt") as applescript:
    subprocess.run(["/usr/bin/osascript", "-e", f"{applescript.read()}\nmyHandler()"])````
1
  • Yuck! No, don't do this. I'll post an answer now. It's very simple once you know how to do it. – CJK Jul 15 '20 at 19:47
0
on myHandler()
   display dialog ("I'm your Handler!")
end myHandler

How do I call myHandler from osascript (using Terminal)

Assuming your shell is bash or zsh, there are a couple of ways, depending on your needs or preferences. You can send your code through directly, which only needs an extra line at the bottom in this case to actually call the handler in order to execute its code (just as you did in your Python code: "{applescript.read()}\nmyHandler()"):

osascript <<-'osa'
    on myHandler()
        display dialog ("I'm your Handler!")
    end myHandler

   myHandler()
osa

If you, say, stored your script in a file, which was located at ~/Documents/myscript.applescript, then you can pass the file into osascript like so:

osascript ~/Documents/myscript.applescript

Of course, you would still need to include the call to your handler in your .applescript file, i.e. an extra line at the end or the beginning of your script that simply says myHandler()

If you wanted to pass a commandline parameter to make the contents of the dialog more dynamic, you can edit your script to look like this:

property text item delimiters: space

on run input as text
    myHandler(input)
end run

on myHandler(msg as text)
    local msg
    display dialog msg
end myHandler

Then call it from the command line like this:

osascript ~/Documents/myscript.applescript "It worked!"

Hopefully, if I anticipated my example script's set up correctly, it should work without the quotes:

osascript ~/Documents/myscript.applescript Do these words have a space between them \?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .