Created
September 12, 2025 04:04
-
-
Save jeofo/088af419d51e4330f8620c088cd555da to your computer and use it in GitHub Desktop.
ZSH Auto .venv
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
| # Auto-activate .venv when entering a directory (search up to 2 parents) | |
| function auto_venv() { | |
| local dir=$PWD venv_path= venv_dir= current_venv= | |
| for i in {0..2}; do | |
| if [[ -f "$dir/.venv/bin/activate" ]]; then | |
| venv_path="$dir/.venv/bin/activate" | |
| break | |
| fi | |
| dir="$(dirname "$dir")" | |
| done | |
| [[ -z $venv_path ]] && return 0 | |
| venv_dir="$(dirname "$(dirname "$venv_path")")" | |
| if command -v realpath >/dev/null 2>&1; then | |
| venv_dir="$(realpath "$venv_dir")" | |
| [[ -n $VIRTUAL_ENV ]] && current_venv="$(realpath "$VIRTUAL_ENV")" | |
| else | |
| venv_dir="${venv_dir:A}" | |
| [[ -n $VIRTUAL_ENV ]] && current_venv="${VIRTUAL_ENV:A}" | |
| fi | |
| if [[ -n $current_venv && $current_venv == "$venv_dir" ]]; then | |
| return 0 | |
| fi | |
| source "$venv_path" | |
| local pyver="$("$VIRTUAL_ENV/bin/python" --version 2>&1)" | |
| echo "🐍 activated venv: $pyver" | |
| } | |
| autoload -U add-zsh-hook | |
| add-zsh-hook chpwd auto_venv | |
| auto_venv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment