Python Environment Variables Tutorial

Advertisement

Advertisement

Introduction

Environment variables are useful way of getting and setting variables that go in to your application. We'll look at how to get and set environment variables using os.environ and how to use python-dotenv to load environment variables.

Get environment variables in Python

In Python, you can get the environment variables through the os.environ object.

You can use it just like a dictionary, using get() to fetch an environment variable or provide a default value.

import os

print(os.environ)
# Get `HOME` environment var, or use the default provided
print(env_vars.get('HOME', '/home/nobody'))

Set environment variables in Python

To set an environment variable, just set a value on os.environ like a regular dictionary.

import os

os.environ['EDITOR'] = 'vim'

Delete environment variables

To delete an environment variable, use the del keyword to remove an element from the object by key name like this:

import os

del os.environ['EDITOR']

Use dotenv to load environment variables

Environment variables are often used to configure an application. You can store environment variables in a .env file that are loaded in your application.

You will first need to install the third-party package python-dotenv.

python -m pip install python-dotenv

An example .env file looks like:

EDITOR=vim
PYTHONPATH=/path/to/extra/modules

To load the environment variables using

# pip install python-dotenv
from dotenv import load_dotenv

# Load environment variables from `.env` file.
load_dotenv()

# Your values are now stored in `os.environ`

Conclusion

After reading this guide you should understand how to get and set environment variables in Python using os.environ or using dotenv.

References

Advertisement

Advertisement