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.

Output:

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

try:
    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 ")
else:
    print("IP not found in environ ")

Output:

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}")

Output:

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
PYTHONIOENCODING > UTF-8
USER > chandra
TMPDIR > /var/folders/g9/g6cfpgy/T/
COMMAND_MODE > unix2003
PS1 > (venv) 
VIRTUAL_ENV > /Users/chandra/Work/MyWork/python_samples/venv
LOGNAME > chandra
LC_CTYPE > en_GB.UTF-8
PWD > /Users/chandra/Work/MyWork/python_samples
PYCHARM_HOSTED > 1
HOME > /Users/chandra

References:

Happy Learning 🙂