6

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?

D-Bug
  • 666
  • 2
  • 8
  • 19

3 Answers3

4

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.

Community
  • 1
  • 1
sakra
  • 62,199
  • 16
  • 168
  • 151
4

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.

Kevin
  • 8,353
  • 3
  • 37
  • 33
  • "set" does not seem to work, but "export" does (I'm using bash on Mac OS X). :~ cls$ export VAR=VALUE :~ cls$ echo $VAR VALUE However, it does not work from Mathematica. In[15]:= Run["export VAR=VALUE"] Out[15]= 0 In[16]:= Environment["VAR"] Out[16]= $Failed Even if I set the variable from the command line, it cannot be retrieved with Environment[]. – D-Bug May 15 '09 at 13:52
2

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.

Yogi
  • 2,460
  • 2
  • 18
  • 17