I try to process command line arguments in a AppleScript. The script works if I run it using osascript TestArgs.scpt a.txt b.txt
. But if I save the script as an .app and run it from the command line, it does not show any arguments: open -a TestArgs --args a.txt b.txt
does not work. I also tried several variations of the script with no success.
on run argv
set argc to 0
try
set argc to (count of argv)
end try
tell application "Finder" to display dialog ("Argument Count: " & argc as string)
end run
It seems the problem is realted to OSX 10.8, as the same script works as expected on 10.7
Where is my mistake?
Thanks and Regards.
There’s a way to do it with JXA (JavaScript for Automation), which may be an acceptable solution. It uses the Objective-C bridge, so it may be possible with AppleScript as well. This was mostly taken from the JXA Cookbook.
The equivalent JXA to the AppleScript in this question would use:
function run(argv) {
…
}
But it suffers from the same issue of not working when compiled to an app. You can get around that by starting your code with
ObjC.import('Foundation')
const args = $.NSProcessInfo.processInfo.arguments
const argv = []
const argc = args.count
for (let i = 0; i < argc; i++) { argv.push(ObjC.unwrap(args.objectAtIndex(i))) }
delete args
User-given arguments will then start at argv[1]
, as argv[0]
will be the applet itself.
Why aren't you using the osascript with the app? That works. You basically have 2 ways to pass args. These work for a scpt or app...
1) from command line: osascript /path/to/script arg1 arg2
2) from another script: run script file path:to:script with parameters {arg1, agr2}.
I have been long searching for a solution myself too. Since there is not an approved solution yet, I would like to point out to the solution posted by red_menace. There you find an AppleScript code which exactly answers the original posted question, how to run an Applescript applications with command line arguments.
To give credits, the AppleScript code there is reminiscent of the JavaScript application posted by user137369.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With