Environment Variables in Python
Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is None.
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
In Python, we use the os
module to interact with environment variables. The os.environ
object is a dictionary-like object that represents the environment variables. We can set new environment variables by assigning to os.environ['KEY']
, and we can retrieve values using os.environ.get('KEY')
, which returns None
if the key doesn’t exist.
To list all environment variables, we can simply iterate over os.environ
. Each key in this dictionary represents an environment variable name.
Note that changes to os.environ
in a Python program only affect the environment of the current process and its child processes. They do not modify the system environment permanently.