Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Environment Variables in Mathematica

I need to set an environment variable from a Mathematica notebook.

Environment["VARIABLE"]

gives the value of the variable. But is it possible to set a variable, too?

like image 285
D-Bug Avatar asked May 12 '09 10:05

D-Bug


3 Answers

There's no built in function (to my knowledge), but you can just use

Run["set VAR=VALUE"]

or

!set VAR=VALUE

instead.

Edit: You'll want to see the documentation for the Run and RunThrough commands.

like image 177
Kevin Avatar answered Nov 11 '22 21:11

Kevin


Environment variables set up with Run or RunThrough will not affect the Mathematica kernel itself but will only be visible to processes launched within the same Run or RunThrough command.

If the environment variable should be visible to the Mathematica kernel process, the gdb based hack described in the accepted answer to Is there a way to change another process's environment variables? can be used under Mac OS X:

SetEnvironment[var_String, value_String] := Module[{valueEscaped, cmd},
    valueEscaped = StringTake[ToString[CForm[value]], {2, -2}];
    cmd = "call (int) putenv (\"" <> var <> "=" <> valueEscaped <> "\")";
    Put[OutputForm[cmd], "!gdb -n \"" <> First[$CommandLine] <> "\" " <> ToString[$ProcessID ]]
]

The Mathematica Put command is used to launch gdb and have it attach itself to the Mathematica kernel process. The gdb command call (int) putenv ("var=value") is then sent to gdb on stdin to set up the environment variable with putenv.

Caveat: Under Mac OS X gdb is only available if the Xcode developer tools are installed.

like image 25
sakra Avatar answered Nov 11 '22 19:11

sakra


I am assuming you are going to do this before you try to run an external command right? Why not instead just run "VARNAME=value; your_original_external_command" that will temporarily set the evn variable.

like image 45
Yogi Avatar answered Nov 11 '22 20:11

Yogi