Python – How to make environment variable changes stick in Python


From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?

The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.

My test code is

import os
os.environ['FAKE'] = 'C:\\'

Opening another instance of Python and requesting os.environ['FAKE'] yields a KeyError.

NOTE: Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.

That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.

Best Solution

You can using SETX at the command-line.

By default these actions go on the USER env vars. To set and modify SYSTEM vars use the /M flag

import os
env_var = "BUILD_NUMBER"
env_val = ""
os.system("SETX {0} {1} /M".format(env_var,env_val))