Embedding IronPython and overwriting Environment Variables
<p>I embed an IronPython interpreter in a C# application to execute a Python script. The script evaluates a specific environment variable <code>VAR1</code> using <code>os.environ['VAR1']</code></p>

<p>I need to change the value of <code>VAR1</code> temporarily before the script is executed. To do this I call</p>

<pre><code>Environment.SetEnvironmentVariable("VAR1", "NEW_VALUE");
</code></pre>

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

<p>Here is a complete example code:</p>

<pre><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()));
</code></pre>

<p>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?</p>

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