I embed an IronPython interpreter in a C# application to execute a Python script. The script evaluates a specific environment variable VAR1 using os.environ['VAR1']
I need to change the value of VAR1 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 VAR1 (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']");
script.Execute();
System.Windows.Forms.MessageBox.Show(Encoding.Unicode.GetString(ms.ToArray()));
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?