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
- Install direnv
sudo apt-get install direnv
- 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)"
- 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
}
- Create a
.envrc
file inside your project folder that triggers the activation of your virtual environment
layout virtualenv ~/myprojectpath/myproject-env