Krid Krid - 2 months ago 15
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

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?

Answer

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(...);
CodeIReallyWantToRun.Execute();
Comments