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.

2
  • 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. Commented Aug 28, 2016 at 0: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. Commented Aug 28, 2016 at 1:04

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@eryksun, excellent points both, updated per %TEMP% suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.