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?

  • See this question: https://apple.stackexchange.com/q/257541/119271 Technically, it’s an unrelated question, but my code does what you’re asking. – Allan Jul 13 '20 at 15:50
  • But how do I dynamically call a subroutine from the command line args? – 5t4cktr4c3 Jul 13 '20 at 16:05
  • the run handler can accept arguments, check out my answer at https://stackoverflow.com/a/57648526/10853463 – red_menace Jul 13 '20 at 17:50

2 Answers2

2
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 \?
CJK
  • 5,512
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()"])````

  • 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