How do I make environment variable changes stick in Python?

Solution 1:

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 = "3.1.3.3.7"
os.system("SETX {0} {1} /M".format(env_var,env_val))

Solution 2:

make them stick by committing them to the system?

I think you are a bit confused here. There is no 'system' environment. Each process has their own environment as part its memory. A process can only change its own environment. A process can set the initial environment for processes it creates.

If you really do think you need to set environment variables for the system you will need to look at changing them in the location they get initially loaded from like the registry on windows or your shell configuration file on Linux.

Solution 3:

Under Windows it's possible for you to make changes to environment variables persistent via the registry with this recipe, though it seems like overkill.

To echo Brian's question, what are you trying to accomplish? There is probably an easier way.

Solution 4:

Seems like there is simplier solution for Windows

import subprocess 
subprocess.call(['setx', 'Hello', 'World!'], shell=True)

Solution 5:

I don't believe you can do this; there are two work-arounds I can think of.

  1. The os.putenv function sets the environment for processes you start with, i.e. os.system, popen, etc. Depending on what you're trying to do, perhaps you could have one master Python instance that sets the variable, and then spawns new instances.

  2. You could run a shell script or batch file to set it for you, but that becomes much less portable. See this article:

http://code.activestate.com/recipes/159462/