Last active
November 8, 2021 10:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ... | |
# Copyright © 2021 Nils Philippsen <[email protected]> | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I often activate a virtual environment (and usually change into its project directory) using
workon <envname>
(ofvirtualenvwrapper
), 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.