2

I have a bat file that sets some environment variables such as

@echo off
SET MY_ENV_VAR=C:\temp

I would like to run this bat file via Python and run other executables that depend on this environment variable bat sets. But even if the bat file runs, I cannot see the environment variables via Python

subprocess.call(['path_to_bat_file\file.bat'], shell = False)
print(os.environ['MY_ENV_VAR'])

I tried to set Shell to True and add other parameters I found on the internet but nothing was successfull. It gives KeyError on os.environ that MY_ENV_VAR is not found. When I run the bat file manually before running the python script, everything works as expected.

Any help is appreciated.

Thank you,

MeCe
  • 445
  • 2
  • 5
  • 12
  • 1
    That is happening because your `subprocess.call()` sets up a *new* process. You set the environment variable there. The batch file ends and the process terminates. The associated environment disappears. In the next line of your code you have the environment with which the Python interpreter started. When you run the .bat file before running the Python code, both the .bat file and the Python code run in the same process. Instead, set your environment variable by directly assigning a value to `os.environ['MY_ENV_VAR']`. – BoarGules Feb 09 '19 at 16:19
  • I couldn't find a way to run the bat file in the main thread. Is it possible? – MeCe Feb 09 '19 at 16:22
  • You don't need to run a .bat file to set Windows environment variables. Which is good, because you can't run a .bat in the main thread. – BoarGules Feb 09 '19 at 16:23
  • 1
    I have 150 environment variables inside the main bat file. I don't want to carry them inside the python script :) – MeCe Feb 09 '19 at 16:25
  • Have the script read them in from the .bat file. It should be easy to parse a bunch of `SET` statements. Unless, of course, they refer to one another, which will make it a little more difficult. – BoarGules Feb 09 '19 at 16:26
  • I was afraid it would come to that decision. – MeCe Feb 09 '19 at 16:27

1 Answers1

2

There is no way to change your environment from a child process. The end :)

But you can change the environment variable from within a script like,

import os
os.environ["MY_ENV_VAR"] = "C:\temp"
han solo
  • 6,390
  • 1
  • 15
  • 19