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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With