Use direnv to switch between virtual environments

Direnv is a tool used in software development, particularly beneficial in DevOps practices. Here's a concise overview:

Why Direnv?

  • Functionality: Automates the process of setting and unsetting environment variables.
  • Scope: Works on a per-directory basis.
  • Integration: Hooks into your shell; compatible with common shells like bash, zsh, tcsh.
  • Flexibility: Loads and unloads environment variables as you move between directories.

How to get started

  1. Install direnv
sudo apt-get install direnv
  1. Add the hook to ~/.bashrc
show_virtual_env() {
  if [[ -n "$VIRTUAL_ENV" && -n "$DIRENV_DIR" ]]; then
    echo "($(basename $VIRTUAL_ENV))"
  fi
}
export -f show_virtual_env
PS1='$(show_virtual_env)'$PS1

# direnv
eval "$(direnv hook bash)"
  1. Add this to your ~/.direnvrc file:
layout_virtualenv() {
  local venv_path="$1"
  source ${venv_path}/bin/activate
  # https://github.com/direnv/direnv/wiki/PS1
  unset PS1
}
  1. Create a .envrc file inside your project folder that triggers the activation of your virtual environment
layout virtualenv ~/myprojectpath/myproject-env