Environment variables are accessed through the os module in python. Here we are going to see the different use cases to read the environment variables.

How to read environment variables?

Environment variables can be set in different ways in different operating systems that I have explained in my previous article. Now we are trying to read them using the python os module.

environ is a dictionary provided by the os module which contains all environment variables.

import os

print('USER > ', os.environ['USER'])
print('HOME > ', os.environ['HOME'])
print('PATH > ', os.environ['PATH'])
print('PYTHONPATH > ', os.environ['PYTHONPATH'])

On the above, I am trying to print some of the environment variables that were already been set on my computer.


USER >  chandra
HOME >  /Users/chandra
PATH >  /Users/chandra/Work/MyWork/python_samples/venv/bin:/usr/bin:/bin:/usr/sbin:/sbin
PYTHONPATH >  /Users/chandra/Work/MyWork/python_samples

KeyError os.environ:

You may get KeyError if the given key is not found in the environment, as the environ is a typical dict object in python.

import os

    print('IP > ', os.environ['IP'])
except KeyError as err:
    print(f"Given key not found - {err}")

Since the IP environment variable not configured in my system I ran into KeyError.

Given key not found - 'IP'

You are open to using .get() method on environ dict to assign the default values to avoid KeyError.

Check specific key exist or not:

We can also check the specific environment variable exist on the system or not.

if 'IP' in os.environ:
    print("IP found in environ ")
    print("IP not found in environ ")


IP not found in environ

Read all environment variables:

If you would like to read all the environment variables?

for item, value in os.environ.items():
    print(f"{item} > {value}")


PATH > /Users/chandra/Work/MyWork/python_samples/venv/bin:/usr/bin:/bin:/usr/sbin:/sbin
PYTHONPATH > /Users/chandra/Work/MyWork/python_samples
SHELL > /bin/zsh
USER > chandra
TMPDIR > /var/folders/g9/g6cfpgy/T/
COMMAND_MODE > unix2003
PS1 > (venv) 
VIRTUAL_ENV > /Users/chandra/Work/MyWork/python_samples/venv
LOGNAME > chandra
PWD > /Users/chandra/Work/MyWork/python_samples
HOME > /Users/chandra


Happy Learning 🙂