This is a short tutorial on how to use dotenv to read key-value pairs from a .env
file and can set them as environment variables.
Python-dotenv assists in the development of applications, following the 12-factor principles.
Installation
I will be using docker to provision a python 3.8 environment, but this step is optional:
docker run -it python:3.8-alpine sh
Install the python-dotenv using pip:
pip install -U pip
pip install python-dotenv
Example Usage
Create a app directory and change to it:
mkdir /app
cd /app
The test file test.py
:
import os
import json
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
json_env = dict(os.environ)
print(json.dumps(json_env, indent=2, default=str))
With no .env
file present we will see the default env vars:
python test.py
{
"HOSTNAME": "2c2f6c81de7e",
"PYTHON_PIP_VERSION": "21.2.4",
"SHLVL": "1",
"HOME": "/root",
"OLDPWD": "/",
"GPG_KEY": "E3FF2839C048B25C084DEBE9B26995E310250568",
"PYTHON_GET_PIP_URL": "https://github.com/pypa/get-pip/raw/3cb8888cc2869620f57d5d2da64da38f516078c7/public/get-pip.py",
"TERM": "xterm",
"PATH": "/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"LANG": "C.UTF-8",
"PYTHON_VERSION": "3.8.12",
"PYTHON_SETUPTOOLS_VERSION": "57.5.0",
"PWD": "/app",
"PYTHON_GET_PIP_SHA256": "c518250e91a70d7b20cceb15272209a4ded2a0c263ae5776f129e0d9b5674309"
}
We can verify that by running env
:
env
HOSTNAME=2c2f6c81de7e
PYTHON_PIP_VERSION=21.2.4
SHLVL=1
HOME=/root
OLDPWD=/
GPG_KEY=E3FF2839C048B25C084DEBE9B26995E310250568
PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/raw/3cb8888cc2869620f57d5d2da64da38f516078c7/public/get-pip.py
TERM=xterm
PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LANG=C.UTF-8
PYTHON_VERSION=3.8.12
PYTHON_SETUPTOOLS_VERSION=57.5.0
PWD=/app
PYTHON_GET_PIP_SHA256=c518250e91a70d7b20cceb15272209a4ded2a0c263ae5776f129e0d9b5674309
Now if we create the .env
file and populate it with one key and value:
cat .env
OWNER=ruanbekker
By running our script again, we can see that the output is our runtime environment variables, plus the one that we defined in the .env
file:
python test.py env
{
"HOSTNAME": "2c2f6c81de7e",
"PYTHON_PIP_VERSION": "21.2.4",
"SHLVL": "1",
"HOME": "/root",
"OLDPWD": "/",
"GPG_KEY": "E3FF2839C048B25C084DEBE9B26995E310250568",
"PYTHON_GET_PIP_URL": "https://github.com/pypa/get-pip/raw/3cb8888cc2869620f57d5d2da64da38f516078c7/public/get-pip.py",
"TERM": "xterm",
"PATH": "/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"LANG": "C.UTF-8",
"PYTHON_VERSION": "3.8.12",
"PYTHON_SETUPTOOLS_VERSION": "57.5.0",
"PWD": "/app",
"PYTHON_GET_PIP_SHA256": "c518250e91a70d7b20cceb15272209a4ded2a0c263ae5776f129e0d9b5674309",
"OWNER": "ruanbekker"
}
Thank You
Thanks for reading, if you enjoy my content feel free to follow me on Twitter at @ruanbekker and subscribe to my newsletter.
Comments