Skip to content

Instantly share code, notes, and snippets.

@nphilipp
Last active November 8, 2021 10:41
Show Gist options
  • Save nphilipp/dd14f54a28ab00ac709b40c7d7fa2b52 to your computer and use it in GitHub Desktop.
Save nphilipp/dd14f54a28ab00ac709b40c7d7fa2b52 to your computer and use it in GitHub Desktop.
Auto-activate Python virtualenvwrapper environment if shell is started within a project directory
# ...
# Copyright © 2021 Nils Philippsen <nils@tiptoe.de>
# Licensed under the MIT license as published by the Open Source Initiative
# Auto-activate Python virtualenvwrapper environment if shell is started within a project directory
_old_nullglob=$(shopt -p nullglob)
shopt -s nullglob
unset _projdirs_venvs
declare -A _projdirs_venvs
for _venvdir in ${WORKON_HOME:-$HOME/.virtualenvs}/*/; do
_projfile="${_venvdir}/.project"
if [ ! -f "$_projfile" ]; then
continue
fi
_venvdir="${_venvdir%%/}"
_projdir="$(tr -d '\0' < "${_venvdir}/.project")"
if [ -z "$_projdir" ]; then
continue
fi
_venv="${_venvdir##*/}"
_projdirs_venvs[$_projdir]="$_venv"
done
unset _projdirs_sorted
declare -a _projdirs_sorted
while read _projdir; do
_projdirs_sorted+=("$_projdir")
done < <(for _projdir in "${!_projdirs_venvs[@]}"; do
echo "$_projdir"
done | sort -r)
for _projdir in "${_projdirs_sorted[@]}"; do
if [ "$PWD" = "$_projdir" -o "${PWD#${_projdir}/}" != "$PWD" ]; then
_venv="${_projdirs_venvs[${_projdir}]}"
workon -n "$_venv"
break
fi
done
eval $_old_nullglob
unset _old_nullglob _projdirs_venvs _venvdir _projfile _projdir _venv
@nphilipp
Copy link
Author

nphilipp commented Nov 7, 2021

I often activate a virtual environment (and usually change into its project directory) using workon <envname> (of virtualenvwrapper), then open a new terminal tab or window which – with e.g. gnome-terminal – starts in the same directory. I usually attempt to run something related to the project there right away – which fails, sometimes more, sometimes less obviously, because the virtual environment isn't active.

The snippet above, if put into ~/.bash_profile for login shells, searches for a virtual environment whose project directory is $PWD or a parent, and activates it. If no virtual environment matches, nothing is done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment