Skip to content

Instantly share code, notes, and snippets.

@bluss
Created October 17, 2024 19:03
Show Gist options
  • Save bluss/2ff36cb8adb73e8c8c4bd55984c142fb to your computer and use it in GitHub Desktop.
Save bluss/2ff36cb8adb73e8c8c4bd55984c142fb to your computer and use it in GitHub Desktop.
# activate venv
# Usage: venv [ENVNAME]
#
# If there is only one venv in the current directory, activates it
# If there are multiple, shows a list where you select.
#
# Dependencies: external program gum for the selection menu
venv()
{
# optional path to environment
local VENV="$1"
if test -z "$VIRTUAL_ENV" ; then
if test -z "$VENV"; then
# Pop up a menu if there are multiple to choose from
local VENVS=$(find . -maxdepth 2 -type f -name "pyvenv.cfg" -exec dirname {} \; | sort)
local NVENVS=$(grep -c -e . <<<"$VENVS")
if (( "$NVENVS" > 1 )); then
printf "Choose virtualenv to activate...\n" >/dev/stderr
VENV=$(gum choose $VENVS)
elif (( "$NVENVS" == 0 )); then
printf "Error: No virtualenvs in directory\n" >/dev/stderr
return 1
else
VENV="$VENVS"
fi
fi
source "$VENV"/bin/activate
else
printf "Error: already in venv\n" >/dev/stderr
return 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment