How to set environment variables for current Command Prompt session from Python
<p>I've been stumped for far too long.  Hoping someone can assist.</p>

<p>I am writing a Python CLI application that needs to set a temporary environment variable (PATH) for the current command prompt session (Windows).  The application already sets the environment variables permanently for all future sessions, using the method seen <a href="https://gist.github.com/apetrone/5937002" rel="nofollow">here</a>.</p>

<p>To attempt to set the temporary env vars for the current session, I attempted the following:</p>

<ul>
<li>using <code>os.environ</code> to set the environment variables</li>
<li>using the answer <a href="http://stackoverflow.com/questions/3636055/how-to-modify-the-path-variable-definitely-through-the-command-line-in-windows">here</a> which makes use of a temporary file.  Unfortunately this works when run directly from the Cmd Prompt, but not from Python.</li>
<li>calling <code>SET</code> using <code>subprocess.call</code>, <code>subprocess.check_call</code></li>
</ul>

<p>The users of the tool will need this so they do not have to close the command prompt in order to leverage the environment variables I've set permanently.</p>

<p>I've see other applications do this, but I'm not sure how to accomplish this with Python.</p>

<p>Brute-force but straightforward is to emit your assignments as a batch script on stdout, and execute that script in the existing interpreter (akin to <code>source</code> in bash):</p>

<pre><code>python myscript &gt;%TEMP%\myscript-vars.bat
call %TEMP%\myscript-vars.bat
del %TEMP%\myscript-vars.bat
</code></pre>

python windows environment-variables