1

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:

  • using os.environ to set the environment variables
  • using the answer here which makes use of a temporary file. Unfortunately this works when run directly from the Cmd Prompt, but not from Python.
  • calling SET using subprocess.call, subprocess.check_call

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.

Community
  • 1
  • 1
dsu66uth
  • 13
  • 1
  • 6
  • 1
    I can't speak definitively to Windows -- but on UNIX, the need for a parent process's cooperation for a subprocess to modify its environment variables (absent tricks such as attaching with a debugger) is entirely intentional and by-design. – Charles Duffy Aug 28 '16 at 00:54
  • 1
    @CharlesDuffy, technically in Windows it's usually possible (but not always) to open a handle to the parent process and rewrite its environment variables -- depending on the parent process DACL, integrity level, and whether it's a 'protected' process. However, I don't think it's ever a good idea. – Eryk Sun Aug 28 '16 at 01:04

1 Answers1

4

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
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 2
    You could run the script from another batch file that handles this automatically. You'd want to write the .bat file to the `%TEMP%` directory because the user may not have write access to the current directory. – Eryk Sun Aug 28 '16 at 00:55
  • @eryksun, excellent points both, updated per `%TEMP%` suggestion. – Charles Duffy Aug 28 '16 at 13:51