How to automatically activate virtualenvs when cd'ing into a directory

后端 未结 12 1993
北海茫月
北海茫月 2020-12-24 06:27

I have a bunch of projects in my ~/Documents. I work almost exclusively in python, so these are basically all python projects. Each one, e.g. ~/Documents/

12条回答
  •  粉色の甜心
    2020-12-24 06:33

    This is a zsh only solution.

    This is an improvement over daveruinseverything's answer which is an improvement over MS_'s answer.

    We are using precmd hook instead of overwriting cd.

    We have added another extra feature. Suppose the directory structure is

    ├── .venv
    │   ├── bin
    │   │   └── activate
    ├── subdir
    │   ├── subdir1
    │   │   ├── subdir2
    │   │   │   └── test2.txt
    │   │   └── test1.txt
    │   └── test.txt
    └── testing.py
    

    If you now open new terminal in subdir2, or directly cd to subdir2 from other place, it will activate the venv.

    The solution is:

    autoload -Uz add-zsh-hook
    add-zsh-hook precmd automatically_activate_python_venv
    
    function automatically_activate_python_env() {
      if [[ -z $VIRTUAL_ENV ]] ; then
        activate_venv
      else
        parentdir="$(dirname ${VIRTUAL_ENV})"
        if [[ "$PWD"/ != "$parentdir"/* ]] ; then
          deactivate
          activate_venv
        fi
      fi
    }
    
    function activate_venv() {  
      local d n
      d=$PWD
      
      until false 
      do 
      if [[ -f $d/.venv/bin/activate ]] ; then 
        source $d/.venv/bin/activate
        break
      fi
        d=${d%/*}
        # d="$(dirname "$d")"
        [[ $d = *\/* ]] || break
      done
    }
    

提交回复
热议问题