2
$\begingroup$

According to https://reference.wolfram.com/language/ref/program/wolframscript.html i can pass arguments to a file containing wolframscript. But i cannot find a way to actually use passed arguments.

wolframscript -file file|url [-cloud [cloudbase] | -local [kernelpath]] [arg1 …]

Is mentioned in the Doccumentation but how do I pass named arguments? I only know how to retrieve said arguments using $ScriptCommandLine[[2;;]] but that seems very unsafe.

There is also mentioned that this file would work

#!/usr/bin/env wolframscript -function -signature City City
GeoDistance[#1, #2]&

yielding this output

$ ./file.wls "New York" London
Quantity[3453.7070027090986, Miles]

my current file is

#!/usr/bin/env wolframscript
(* ::Package:: *)

Print[$ScriptCommandLine[[2]]]
Print[#1]

But i do not know how to add this signature to my file (without nano and similair programs)

$\endgroup$
3
$\begingroup$

I'm not sure I understand what you are asking for, but here is a script that runs in Terminal on macOS 1013.4 and uses arguments from the command line.

#!/Applications/Mathematica.11.3.0.app/Contents/MacOS/wolframscript
(* ::Package:: *)

argv = Rest @ $ScriptCommandLine;
argc = Length @ argv;
Do[Print[argv[[i]]], {i, argc}]

This is what the script in a terminal session looks like:

output

Does this clarify the issue of how command line arguments are used in a Mathematica script?

$\endgroup$
  • $\begingroup$ I got that, but i wanted to know whether there is a way to do this without $ScriptCommandLine like in the example from the wiki. But i guess this is good enough. $\endgroup$ – Gladaed Feb 28 at 12:41
1
$\begingroup$

Here's what I do on MacOSX and Linux. I have a file wolfram_command.wls that contains:

#!/usr/bin/env wolframscript -function

My notebook is set up to autosave a .m file, and I've arranged it so that evaluating the file yields a head that makes sense as a function, either a named function or an anonymous Function. Then, to make an executable, I use the following commands:

cat wolfram_command.wls mything.m >mycommand

chmod +x mycommand

I actually put those commands in a Makefile, but I think that's out of scope here. When mycommand is executed from command line, the function mything.m yields is evaluated with the command line arguments as arguments.

It would be nice if there was some option that let you set the arguments to wolframscript in the notebook, for when you save a .wls, but there doesn't seem to be any such thing.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.