Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change environment variables persistently with Python

Is it possible using Python 3.5 to create and update environment variables in Windows and Linux so that they get persisted?

At the moment I use this:

import os
os.environ["MY_VARIABLE"] = "TRUE"

However it seems as if this does not "store" the environment variable persistently.

like image 800
Robert Strauch Avatar asked Feb 08 '23 00:02

Robert Strauch


1 Answers

I'm speaking for Linux here, not sure about Windows.

Environment variables don't work that way. They are a part of the process (which is what you modify by changing os.environ), and they will propagate to child processes of your process (and their children obviously). They are in-memory only, and there is no way to "set and persist" them directly.

There are however several configuration files which allow you to set the environment on a more granular basis. These are read by various processes, and can be system-wide, specific to a user, specific to a shell, to a particular type of process etc.

Some of them are:

  • /etc/environment for system-wide variables
  • /etc/profile for shells (and their children)
  • Several other shell-specific files in /etc
  • Various dot-files in a user's home directory such as .profile, .bashrc, .bash_profile, .tcshrc and so on. Read your shell's documentation.
  • I believe that there are also various ways to configure environment variables launched from GUIs (e.g. from the gnome panel or something like that).

Most of the time you'll want to set environment variables for the current user only. If you only care about shells, append them to ~/.profile in this format:

NAME="VALUE"

like image 134
AaronI Avatar answered Feb 12 '23 12:02

AaronI