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

后端 未结 12 1941
北海茫月
北海茫月 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:45

    Based on @MS_'s solution:

    function cd() {
      builtin cd "$@"
    
      ## If env folder is found then activate the vitualenv
      if [[ -d ./venv ]] ; then
        source ./venv/bin/activate
      fi
    
      if [[ -n "$VIRTUAL_ENV" ]] ; then
        ## check the current folder belong to earlier VIRTUAL_ENV folder
        # if yes then do nothing
        # else deactivate
          parentdir="$(dirname "$VIRTUAL_ENV")"
          if [[ "$PWD"/ != "$parentdir"/* ]] ; then
            deactivate
          fi
      fi
    }
    

提交回复
热议问题