Krid Krid - 1 year ago 172
C# Question

Embedding IronPython and overwriting Environment Variables

I embed an IronPython interpreter in a C# application to execute a Python script. The script evaluates a specific environment variable


I need to change the value of
temporarily before the script is executed. To do this I call

Environment.SetEnvironmentVariable("VAR1", "NEW_VALUE");

in the C# code. Unfortunately this does not work. The Python script still "sees" the old value of
(the value it had when the hosting C# application started).

Here is a complete example code:

Environment.SetEnvironmentVariable("VAR1", "NEW_VALUE");
var engine = Python.CreateEngine();
engine.SetSearchPaths(new string[] { @"c:\Program Files (x86)\IronPython 2.7\Lib\" });
var ms = new MemoryStream();
engine.Runtime.IO.SetOutput(ms, Encoding.Unicode);

var script = engine.CreateScriptSourceFromString("import os\nprint os.environ['VAR1']");


My understanding is that the IronPython engine runs in the same process as the C# host application. If this is correct, how can the Python code and the C# code see different environment variables?

Is there a better (working) way to set an environment variable for the Python script?

Answer Source

Well, I still don't know why the above code doesn't work but one can simply set an environment variable in the Python environment by executing Python code that sets the variable BEFORE executing the real code:

engine.CreateScriptSourceFromString("import os\nos.environ['VAR1'] = 'NEW_VALUE'").Execute();
var CodeIReallyWantToRun = engine.CreateScriptSourceFromFile(...);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download