Python 3: How to Read Environment Variables

Sunil Kumar
2 min readJan 22, 2023

There are several ways to read environment variables in Python, but some common methods include

  1. Using the os.environ module: This module provides a dictionary-like interface to the environment variables, where the keys are the variable names and the values are the corresponding values. Example: os.environ['MY_VAR']
  2. Using the os.getenv() function: This function allows you to retrieve the value of a specific environment variable. Example: os.getenv('MY_VAR')
  3. Using the environ from os from dotenv package: This package allows to load of environment variables from a .env file, which is helpful for development and testing. You can install it via pip pip install python-dotenv, and then you can use os.environ.get or os.getenv() function to read the variables from the .env file.

Please note that in order to use the above ways in your python code, you should have the environment variables set in your system before running the code

Here’s an example of using the os.environ object to read an environment variable in Python:

import os
# Set an environment variable
os.environ['MY_VARIABLE'] = 'my_value'
# Retrieve the value of an environment variable
my_variable = os.environ['MY_VARIABLE']
print(my_variable) # Output: 'my_value'

--

--

Sunil Kumar
Sunil Kumar

Written by Sunil Kumar

With an extensive professional experience spanning over 16 years in the IT industry, I am a seasoned expert in AWS Cloud, DevOps, FastAPI, and Python.

No responses yet