Why does providing an environment to my Python subprocess cause it to abort?
<p>I am attempting to run a subprocess through Python of an executable developed by my company; let's call it <code>prog.exe</code>.  I can run this command just fine on from CMD; I can run it just fine through <code>subprocess</code>; but if I try to pass <code>env</code> to <code>subprocess</code>, I get an error:</p>

<pre><code>C:\Users\me&gt; prog.exe -h
prog V1.2.2 (Build 09-07-2016.12.52)
more dummy help text...
C:\Users\me&gt; python
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; import subprocess
&gt;&gt;&gt; import os
&gt;&gt;&gt; subprocess.Popen("prog.exe -h").wait()
prog V1.2.2 (Build 09-07-2016.12.52)
more dummy help text...
0
&gt;&gt;&gt; 
&gt;&gt;&gt; subprocess.Popen("prog.exe -h", env=os.environ).wait()
</code></pre>

<p>After executing that command, the following dialog opens informing me that "<code>prog.exe</code> has stopped working" and "Windows is checking for a solution to the problem...":</p>

<p><a href="http://i.stack.imgur.com/KNukk.png" rel="nofollow"><img src="http://i.stack.imgur.com/KNukk.png" alt="prog.exe has stopped working"></a></p>

<p>which turns into "A problem caused the program to stop working correctly.  Windows will close the program and notify you if a solution is available.":</p>

<p><a href="http://i.stack.imgur.com/S2wMj.png" rel="nofollow"><img src="http://i.stack.imgur.com/S2wMj.png" alt="prog.exe has truly stopped working"></a></p>

<p>When I close that dialog, the subprocess exits with an error:</p>

<pre><code>255
&gt;&gt;&gt;
</code></pre>

<p>What is going on?  I thought that <code>os.environ</code> is essentially passed as <code>env</code> to <code>subprocess</code> if I do not specify <code>env</code>.  So why when I specify it does it cause my program to die?</p>

<p>I have tried Python 3.5 and Python 2.7 with same results.</p>

<p>As described <a href="http://stackoverflow.com/a/19023293/1449189">in an older SO post</a>, the <code>os.environ</code> keys are stored/accessed in a case insensitive manner.  <code>nt.environ</code> preserves the case of the environment variables as passed into the Python process.</p>

<p>In this case, <code>prog.exe</code> is evidently accessing environment variables in a case sensitive manner, thus it requires the original mixed-case environment to be passed in.</p>

<p>Using <code>nt.environ</code> rather than <code>os.environ</code> resolves the issue:</p>

<pre><code>&gt;&gt;&gt; import nt
&gt;&gt;&gt; subprocess.Popen("prog.exe -h", env=nt.environ).wait()
prog V1.2.2 (Build 09-07-2016.12.52)
more dummy help text...
0
&gt;&gt;&gt; 
</code></pre>

python windows subprocess case-sensitive