Get and Set env vars in Python on Windows

Viewed 1442

I'm trying to set an env variable which I want it to be reachable from another windows shell (which is already opened) :

I have tried:

os.environ['start'] = 'test'

Then in a Windows cmd : env.exe | findstr 'start' returns nothing. Variable 'start' does not exist.

Then I tried:

subprocess.call(['setx.exe', 'start', 'test'])
SUCCESS: Specified value was saved

env.exe | findstr 'start' still returns nothing.

How can I get this variable from a windows shell ? Using Windows 10 and python 3. Thanks!

1 Answers

You have to call the Windows SETX from your python code in order to make your environment value saved from your code

os.system("SETX {0} {1} /M".format("start", "test"))

should do the trick. Dont forget to run your script as Administrator. In order for your command prompt to see the changes, make sure you close it and open a new command prompt, then try to find your environment value using env.exe

Related