Is it possible to call init_env.bat
from python in a way that allows
init_env.bat
to alter the environment of the calling scripts
process?
Not easily, although, if the init_env.bat
is really simple, you could attempt to parse it, and make the changes to os.environ
yourself.
Otherwise it's much easier to spawn it in a sub-shell, followed by a call to set
to output the new environment variables, and parse the output from that.
The following works for me...
init_env.bat
@echo off
set FOO=foo
set BAR=bar
foobar.bat
@echo off
echo FOO=%FOO%
echo BAR=%BAR%
main.py
import sys, os, subprocess
INIT_ENV_BAT = 'init_env.bat'
FOOBAR_EXE = 'foobar.bat'
def init_env():
vars = subprocess.check_output([INIT_ENV_BAT, '&&', 'set'], shell=True)
for var in vars.splitlines():
k, _, v = map(str.strip, var.strip().partition('='))
if k.startswith('?'):
continue
os.environ[k] = v
def main():
init_env()
subprocess.check_call(FOOBAR_EXE, shell=True)
subprocess.check_call(FOOBAR_EXE, shell=True)
if __name__ == '__main__':
main()
...for which python main.py
outputs...
FOO=foo
BAR=bar
FOO=foo
BAR=bar
Note that I'm only using a batch file in place of your foobar.exe
because I don't have a .exe
file handy which can confirm the environment variables are set.
If you're using a .exe
file, you can remove the shell=True
clause from the lines subprocess.check_call(FOOBAR_EXE, shell=True)
.