How do you access ARGV in Mathematica?
Asked Answered
M

3

6

I'd like to write command line scripts in Mathematica, but I can't seem to find an Argv[i_Integer] like function. (The docs are FANTASTIC otherwise.)

Mammon answered 1/11, 2011 at 20:44 Comment(1)
similar question: If doing “math foo bar”, how to get foo and bar inside Mathematica?Downtrodden
M
4

$CommandLine works for Mathematica, MathematicaScript, MathKernel, and math.

args.ma:

#!/usr/bin/env MathKernel -script

Print[$CommandLine]

Example:

$ ./args.ma a b c
{"MathKernel", "-script", "./args.ma", "a", "b", "c"}
Mammon answered 2/11, 2011 at 17:18 Comment(0)
A
6

It seems that $ScriptCommandLine is the variable you would need for this, assuming you're using MathematicaScript for scripting. If you use math or MathKernel -script it would be $CommandLine.

Other relevant discussions: a rather old one and one in the MMA toolbag.

Arronarrondissement answered 1/11, 2011 at 20:52 Comment(11)
Thanks. Unfortunately, MathKernel reports $ScriptCommandLine as empty {}, no matter the actual arguments supplied. And MathematicaScript reports Could not find Mathematica installation directory.Mammon
@Mammon Are the executables on your path?Arronarrondissement
@Mammon .... and did you see this line in the docs: "The first line of the script must contain the -script option, which must be the last option on the line."Arronarrondissement
@Mammon "If no -script option was provided, $ScriptCommandLine gives an empty list."Arronarrondissement
@Mammon This all still assuming you're using MathematicaScript.Arronarrondissement
@Mammon What's the value of $InstallationDirectory when you run Mathematica from the frontend?Palestrina
$InstallationDirectory = "/Applications/Mathematica.app", from both MathKernel -script and from the Mathematica GUI.Mammon
@Mammon MathematicaScript is new in v8. What version do you have?Warble
@Mammon It seems my assumption you were using MathematicaScript was wrong. In that case you should try $CommandLine.Arronarrondissement
Congrats on 10k, Sjoerd! Welcome to the club of deleted crap viewers :)Hairpiece
@yoda Thanks, and now the Mathematica gold badge, that'll impress my kids ;-)Arronarrondissement
M
4

$CommandLine works for Mathematica, MathematicaScript, MathKernel, and math.

args.ma:

#!/usr/bin/env MathKernel -script

Print[$CommandLine]

Example:

$ ./args.ma a b c
{"MathKernel", "-script", "./args.ma", "a", "b", "c"}
Mammon answered 2/11, 2011 at 17:18 Comment(0)
A
1

I'm fond of passing things in using environment variables:

http://reference.wolfram.com/mathematica/ref/Environment.html

Agonist answered 2/11, 2011 at 1:7 Comment(1)
Helpful, but it's a bit more manual than specifying command line flags.Mammon

© 2022 - 2024 — McMap. All rights reserved.