Skip to content

Instantly share code, notes, and snippets.

@truetug
Created August 27, 2023 11:02
Show Gist options
  • Save truetug/c05254cba0a5f413bd2b37ba82411bdf to your computer and use it in GitHub Desktop.
Save truetug/c05254cba0a5f413bd2b37ba82411bdf to your computer and use it in GitHub Desktop.
Fast and simple function to automagicaly find and activate python virtual environment with venv
# virtualenv
virtualenv_find_and_activate() {
local ENV_DIR="env"
[ ! -z "${1}" ] && ENV_DIR=$1
local CURRENT=$(pwd)
local ROOT=${CURRENT}
local RESULT=0
while [ "${ROOT}" != "/" ] && [[ "${RESULT}" == 0 ]]; do
local DIRS=( "${ROOT}/${ENV_DIR}" "${ROOT}_${ENV_DIR}" )
for X in ${DIRS[@]}; do
[ -d "${X}" ] && RESULT="${X}"
done
[[ "${RESULT}" == 0 ]] && ROOT=$(dirname "${ROOT}")
done
if [[ "${RESULT}" != 0 ]]; then
ENV="${RESULT}"
SRC="${ENV}/bin/activate"
[ -f ${SRC} ] && . ${SRC} && echo "Activate \"${ENV}\" virtualenv" || echo "Broken ${ENV} virtualenv"
else
echo "Virtualenv \"${ENV_DIR}\" not found"
RESULT=${CURRENT}_${ENV_DIR}
echo -n "Create \"${RESULT}\"? (Y/n): "
read ANSWER
ANSWER=${ANSWER:-Y}
if [ "${ANSWER}" = "Y" ] || [ "${ANSWER}" = "y" ]; then
echo "Creating virtualenv..."
python -m venv ${RESULT}
pva
fi
fi
}
alias pva=virtualenv_find_and_activate
alias pvd=deactivate
@truetug
Copy link
Author

truetug commented Aug 27, 2023

pva-pvd

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