D-Bug
D-Bug

Reputation: 666

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?

Upvotes: 6

Views: 1157

Answers (3)

sakra
sakra

Reputation: 65831

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.

Upvotes: 4

Kevin
Kevin

Reputation: 8561

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.

Upvotes: 4

Yogi
Yogi

Reputation: 2540

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.

Upvotes: 2

Related Questions