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

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

    This is my solution:

    1. If VIRTUAL_ENV is not set then:
      1. Check if we're inside a virtual env
      2. If yes, then activate it
    2. Else (VIRTUAL_ENV is defined), check that the current folder starts with $VIRTUAL_ENV (removing the /venv part) and verify that the deactivate command exists
      1. Deactivate teh environment

    This is the script:

    function cd() {
      builtin cd $1
    
      if [[ -z "${VIRTUAL_ENV}" ]]; then
        if [[ -d ./venv && -f ./venv/bin/activate ]]; then
          source ./venv/bin/activate
        fi
      elif [[ ! "$(pwd)" == ${VIRTUAL_ENV:0:n-5}* && ! -z "$(command -v deactivate)" ]]; then
        deactivate
      fi
    }
    

    Note: You need to add this to .bashrc. If it doesn't work, check if your .profile is not overriding your command (it happened to me)

提交回复
热议问题