Mathematica script - passing command line arguments
Solution (tested on Linux)
Use this as first line of your script:
#!/usr/local/bin/MathematicaScript -runfirst "$TopDirectory=\"/usr/local/Wolfram/Mathematica/8.0\"" -script
If you installed Mathematica in a different directory, you have to adjust the path of $TopDirectory
.
How did I debug this?
The first error message is quite clear: the system cannot open the file /SystemFiles/CharacterEncodings/ISO8859-1.m
and obviously the system is correct, because this file does not exist in this directory.
You could now use strace
to track down what happens (maybe you better redirect the output into a file)
strace -s 128 ./script.m 1 2 3 4 5
Looking into the output you probably stumble over the line
execve(
"/usr/local/Wolfram/Mathematica/8.0/SystemFiles/Kernel/Binaries/Linux-x86-64/MathKernel",
["", "-runfirst", "$TopDirectory=\"/usr/local/Wolfram/Mathematica/8.0\"", "-script",
"./script.m", "--", "./script.m", "1", "2", "3", "4", "5"]
, [/* 54 vars */]) = 0
You see that basically you script-call is of course just a call to the MathKernel
. If you execute this on the command-line, your script runs fine. This seems to suggest, that by providing 5 or more parameters, the setting of the $TopDirectory
is somehow removed. Therefore, I tried to set it explicitly in the MathematicaScript
-call which seems to work.
I get two kinds of errors (different from yours) on Mma 8.0.4 Mac OSX, depending on the number of arguments:
(with the appropriate path for Mac OSX)
#!/Applications/Mathematica.app/Contents/MacOS/MathematicaScript -script
Print[$ScriptCommandLine]
With 5 arguments, I get
error: 14: Bad address
and with 7 or more arguments, I get a segfault:
MathematicaScript(14538) malloc: * error for object 0x70000037: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug Segmentation fault: 11
A workaround is to change MathematicaScript
to MathKernel
, and use $CommandLine[[3;;]]
instead of $ScriptCommandLine
.
I can't reproduce this exactly on win7 mma 8.0.1. $ScriptCommandLine
is empty, while $CommandLine
returns
{"d:\\Math\\Mathematica\\8.0\\math.exe", "-noprompt", "-script", "./script.m", "a=6", "z=3", "d=423", "c=43", "x=1"}
As a workaround have you thought about using environment variables to pass information to your script? You can retrieve the value of an environment variable with a simple Environment["NAME_OF_VARIABLE"]