Kodeclik Logo

Our Programs

Courses

Gifting

Learn More

Schedule

Kodeclik Blog

How to access environment variable values in Python

Environment variables are variables that are set in the operating system and can be accessed by different programs. They are useful for storing configuration values or other information that needs to be shared between different applications. In Python, we can access environment variables using the os module. In this blog post, we will discuss two different ways to access environment variable values in Python.

Method 1: Use the os.environ dictionary variable

The first approach is to use the os.environ dictionary variable. As the name indicates, a dictionary is a collection of (key, value) pairs. The os module provides a dictionary-like object called environ that contains the current environment variables as key-value pairs. We can use this dictionary to access environment variables as follows:

import os

print(os.environ)

You will get a huge output that might look like:

environ({'COLORTERM': 'truecolor', '_PYTHON_HOST_PLATFORM':
'linux-x86_64', 'PYTHONBIN': '/nix/store
hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/bin/python3.10',
'NIX_BUILD_CORES': '16', 'file': 'main.py', 'nativeBuildInputs': '',
'name': 'nix-shell', 'depsHostHostPropagated': ''})

(Your particular output will vary.) As you can see from the output, the collection of environment variables is a dictionary of (key, value) pairs. Thus there is a key called “COLORTERM” which is set to “truecolor” and so on. If you would like to access any particular environment variable, you can access with the name of the variable as the key, like so:

import os

print(os.environ['COLORTERM'])

This will output:

truecolor

Another useful environment variable is “HOME” which refers to the home directory. So if we try:

import os

print(os.environ['HOME'])

We will get something like:

Get the value of an environment variable in Python

/home/runner

(Again, your output might be different.)

Method 2: Use the os.getenv() method

The second approach is to use the os.getnev method that directly returns the value for a given environment variable.

Thus if we try:

import os

print(os.getenv('HOME'))

We will get:

/home/runner

Note that getenv is a function that takes an argument as input (using parentheses) whereas environ is a dictionary that we index (using square brackets).

Let us now try using both approaches above with variables that don’t exist. First, let us try os.environ:

import os

print(os.environ['SOMETHING'])

we will get:

Traceback (most recent call last):
File "main.py", line 3, in <module>
  print(os.environ['SOMETHING'])
File "/nix/store/python3-3.10.8/lib/os.py", line 680, 
  in __getitem__
  raise KeyError(key) from None
KeyError: 'SOMETHING'

Thus Python complains that the key doesn’t exist.

If we try with getenv:

import os

print(os.getenv('SOMETHING'))

we obtain:

None

Thus, getenv gives you a graceful “None” as the answer whereas the environ dictionary complains that such a key does not exist. This is a key difference between these two methods.

If you like you can first check if the given key exists using a separate function, like so:

import os

def check_if_env_variable_exists(x):
if x in os.environ:
  print("The env variable " + x + " exists!")
else:
    print("Sorry, your env variable " + x + " does not exist.")

check_if_env_variable_exists('SOMETHING')
check_if_env_variable_exists('PATH')

The output will be:

Sorry, your env variable SOMETHING does not exist.
The env variable PATH exists!

So in conclusion, we discussed two ways to access environment variable values in Python. We used the os.environ dictionary to access environment variables as key-value pairs, and we used the os.getenv() function to get the value of a specific environment variable. Both methods are valid and produce the same result, but the second one is ideal if the key/variable you are looking for does not exist. In the former case, when used with a non-existent key you need to use exception handling to gracefully trap the error. It is good programming practice to first check if the key exists before attempting to do something with it.

If you liked learning how to get access to environment variables, learn how to set environment variables. Also learn more about finding Python parent paths using the os.path module!

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.