Skip to content

Instantly share code, notes, and snippets.

@aaronedev
Created September 6, 2025 07:52
Show Gist options
  • Select an option

  • Save aaronedev/b443984e78b0329bc07e607065cf8add to your computer and use it in GitHub Desktop.

Select an option

Save aaronedev/b443984e78b0329bc07e607065cf8add to your computer and use it in GitHub Desktop.
automatically source venv using direnv
# .envrc — prefer `workon py_env`, fallback to common venv locations
project_env='py_env'
# if workon is already available, use it
if type workon >/dev/null 2>&1; then
workon "$project_env"
return
fi
# try to source virtualenvwrapper to get workon
if [ -z "${VIRTUALENVWRAPPER_SCRIPT:-}" ]; then
if [ -f "$HOME/.local/bin/virtualenvwrapper.sh" ]; then
export VIRTUALENVWRAPPER_SCRIPT="$HOME/.local/bin/virtualenvwrapper.sh"
elif [ -f "/usr/local/bin/virtualenvwrapper.sh" ]; then
export VIRTUALENVWRAPPER_SCRIPT="/usr/local/bin/virtualenvwrapper.sh"
fi
fi
if [ -n "${VIRTUALENVWRAPPER_SCRIPT:-}" ] && [ -f "$VIRTUALENVWRAPPER_SCRIPT" ]; then
source "$VIRTUALENVWRAPPER_SCRIPT"
if type workon >/dev/null 2>&1; then
workon "$project_env"
return
fi
fi
# final fallback: add venv bin to PATH
if [ -d "./$project_env" ]; then
export VIRTUAL_ENV="$PWD/$project_env"
PATH_add "$VIRTUAL_ENV/bin"
elif [ -d "$HOME/.virtualenvs/$project_env" ]; then
export VIRTUAL_ENV="$HOME/.virtualenvs/$project_env"
PATH_add "$VIRTUAL_ENV/bin"
elif [ -d "./.venv" ]; then
export VIRTUAL_ENV="$PWD/.venv"
PATH_add "$VIRTUAL_ENV/bin"
else
echo "direnv: virtualenv '$project_env' not found"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment