Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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.

like image 373
Soviut Avatar asked Jan 28 '09 16:01

Soviut


People also ask

How do you set a permanent environment variable in Python?

To set and get environment variables in Python you can just use the os module: import os # Set environment variables os. environ['API_USER'] = 'username' os. environ['API_PASSWORD'] = 'secret' # Get environment variables USER = os.

How do I change environment variables in Python?

To permanently modify the default environment variables, click Start and search for 'edit environment variables', or open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you can add or modify User and System variables.

Do environment variables persist?

Environment variables are variables that contain values necessary to set up a shell environment. Contrary to shell variables, environment variables persist in the shell's child processes.


1 Answers

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)) 
like image 164
Jordan Stefanelli Avatar answered Sep 28 '22 00:09

Jordan Stefanelli