1
votes

I need to write a script, on Windows, that calls a batch file to set some environment variables, then carries out some actions that make use of those environment variables.

If the calling script is itself a batch file, this works fine.

There would be some advantages to being able to write the calling script in Python, but when I try that, the environment variables set by the batch file don't persist after it returns. I'm guessing that's because subprocess.check_call(..., shell=True) spawns a fresh copy of the command shell, which takes the environment variables with it when it dies at the end of the batch file.

Is there a way to get the environment variables to persist when set by a batch file called from Python, or is it better to resign oneself to the calling script being itself a batch file?

1
why not just set the environmental variables right in python with os.environ? Im confused on why you need to call this other script - Joran Beasley
@JoranBeasley Because I didn't write the batch file; it's the one that ships with Microsoft C++ to set the environment variables for the compiler. I could reverse engineer it, of course, but then for all I know the result might be incorrect for the next version of Microsoft C++. - rwallace
oh I c ... could you not write a batch file that called those other batchfiles and then called the python script(so it got the environmental variables)? afaik there is no way to pass a childs environmental variables back to the parent - Joran Beasley
@JoranBeasley True; it would be cleaner to have my script be in one file, but I can split it into two files if necessary. - rwallace
Copy or reuse the code from distutils.msvc9compiler.query_vcvarsall. Notice how it adds & set to the command to output the environment variables. - Eryk Sun

1 Answers

1
votes

Use Setx to set variables. New Cmd prompts will pick up straight away, other programns after a reboot. The existing one won't pick it up. Use Set for that.

Rem Add filter.bat to the path if not in there, setx fails if it's already there

setx path %~dp0;%path% 1>nul 2>nul