Created
July 12, 2023 12:32
-
-
Save Winand/500d57c1247cfae52de1ab5e43c021b6 to your computer and use it in GitHub Desktop.
Python virtual environment list and activation script
This file contains hidden or 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
ROOT=~/venv | |
RED='\e[0;31m' | |
GREEN='\e[0;32m' | |
LIGHTBLUE='\e[1;34m' | |
NC='\e[0m' # No Color | |
trim() { | |
# Remove the leading and trailing whitespaces | |
# https://stackoverflow.com/a/12973694 | |
echo $1 | xargs | |
} | |
printEnvList() { | |
echo "Environment list:" | |
for env in "${!venvs[@]}"; do | |
echo -en "- ${GREEN}$env${venvs[$env]}${NC}" | |
[[ -f $ROOT/$env/motd ]] && echo " - "`cat $ROOT/$env/motd` || echo | |
done | |
} | |
banner() { | |
# Show text in a frame | |
# https://unix.stackexchange.com/a/250094 | |
msg="$*" | |
edg=$(echo "$msg" | sed 's/./─/g') | |
echo "┌─$edg─┐" | |
echo "│ $msg │" | |
echo "└─$edg─┘" | |
} | |
unset venvs # required when called using `source` command | |
declare -A venvs | |
for f in $ROOT/*; do | |
# [[ -e $f ]] || continue | |
if [[ -L $f ]]; then | |
src_dir=$(readlink $f) | |
alias_name=$(basename $f) | |
if [[ -f $src_dir/bin/activate ]]; then | |
venvs[`basename $src_dir`]+=" | $alias_name" | |
else echo -e "${RED}!! $src_dir ($alias_name) is not a virtual environment${NC}" | |
fi | |
elif [[ -d $f ]]; then | |
if [[ -f $f/bin/activate ]]; then | |
venvs[`basename $f`]+="" | |
else echo -e "${RED}!! $f is not a virtual environment${NC}" | |
fi | |
fi | |
done | |
if [[ -z $1 ]]; then | |
echo -e "Environment search path: ${GREEN}$ROOT${NC}" | |
echo "Usage:" | |
echo -e "- ${GREEN}. environ${NC} - show help and environment list" | |
echo -e "- ${GREEN}. environ ENV_NAME${NC} - activate environment" | |
# https://stackoverflow.com/a/38462237 | |
echo -e "- ${GREEN}echo \"some text\" > $(cd "$ROOT" && dirs)/ENV_NAME/motd${NC} - set environment description" | |
echo | |
printEnvList | |
elif [[ -f $ROOT/$1/bin/activate ]]; then | |
echo -e "${LIGHTBLUE}Activating $1 virtual environment...${NC}" | |
[[ -f $ROOT/$1/motd ]] && banner `cat $ROOT/$1/motd` | |
command -v deactivate &> /dev/null && deactivate | |
source $ROOT/$1/bin/activate | |
else echo -e "${RED}Error: Virtual environment \"$1\" not found${NC}" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment