7

Python Environment Variables Tutorial

 3 years ago
source link: https://www.devdungeon.com/content/python-environment-variables-tutorial
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK