feat(python): add auto venv activation (#12248)

Co-authored-by: Carlo Sala <carlosalag@protonmail.com>
This commit is contained in:
Robert Crews
2024-03-03 04:04:19 -08:00
committed by GitHub
parent 97a86ed167
commit 12cd3b3e39
2 changed files with 32 additions and 7 deletions

View File

@ -51,11 +51,12 @@ alias pyserver="python3 -m http.server"
## venv utilities
: ${PYTHON_VENV_NAME:=venv}
# Activate a the python virtual environment specified.
# If none specified, use 'venv'.
# If none specified, use $PYTHON_VENV_NAME, else 'venv'.
function vrun() {
local name="${1:-venv}"
local name="${1:-$PYTHON_VENV_NAME}"
local venvpath="${name:P}"
if [[ ! -d "$venvpath" ]]; then
@ -72,12 +73,26 @@ function vrun() {
echo "Activated virtual environment ${name}"
}
# Create a new virtual environment, with default name 'venv'.
# Create a new virtual environment using the specified name.
# If none specfied, use $PYTHON_VENV_NAME
function mkv() {
local name="${1:-venv}"
local name="${1:-$PYTHON_VENV_NAME}"
local venvpath="${name:P}"
python3 -m venv "${name}" || return
echo >&2 "Created venv in '${venvpath}'"
vrun "${name}"
}
if [[ "$PYTHON_AUTO_VRUN" == "true" ]]; then
# Automatically activate venv when changing dir
auto_vrun() {
if [[ -f "${PYTHON_VENV_NAME}/bin/activate" ]]; then
source "${PYTHON_VENV_NAME}/bin/activate" > /dev/null 2>&1
else
(( $+functions[deactivate] )) && deactivate > /dev/null 2>&1
fi
}
add-zsh-hook chpwd auto_vrun
auto_vrun
fi