Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppleScript as .app does not take arguments from command line

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.

like image 297
Daniel Avatar asked Jan 19 '13 22:01

Daniel


3 Answers

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.

like image 127
user137369 Avatar answered Nov 15 '22 21:11

user137369


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}.

like image 26
regulus6633 Avatar answered Nov 15 '22 22:11

regulus6633


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.

like image 28
Andrea Alberti Avatar answered Nov 15 '22 22:11

Andrea Alberti