dsu66uth
dsu66uth

Reputation: 13

How to set environment variables for current Command Prompt session from Python

I've been stumped for far too long. Hoping someone can assist.

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 here.

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

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.

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

Upvotes: 1

Views: 2741

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295520

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 source in bash):

python myscript >%TEMP%\myscript-vars.bat
call %TEMP%\myscript-vars.bat
del %TEMP%\myscript-vars.bat

Upvotes: 4

Related Questions