Setting environment variables in a Python virtualenv from a .env file

Lately, I’ve gotten into the practice of storing configuration in environment variables and keeping those in a .env file in the root of my project directory.

This file contains simple environment variable assignment and is used by Heroku and Docker.

However making sure these environment variables get set for any command being run in the development environment.

I often work in Python virtual environments, so putting the shell commands in the postactivate and postdeactivate scripts makes sense to me.

To set environment variables in postactivate:

#!/bin/bash
# This hook is sourced after this virtualenv is activated.
cd ~/workspace/scrape-represent-statements
set -a
source .env
set +a

To unset environment variables in postdeactivate:

#!/bin/bash
# This hook is sourced after this virtualenv is deactivated.
while read var; do unset $var; done < <(cat .env | grep -v '^\s*#' | sed  's/\s*\([^=]*\)=.*/\1/')