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

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

    Here is (yet) another solution to automatically activate a virtual environment; it's based on a number of the answers already posted here.

    This will work for any Virtual Environment name or directory (not just ./env, ./venv, etc.). Also supports subdirectories, as well as cd-ing into symlinks of virtual environment (parent) folders.

    This code searches for a pyvenv.cfg file instead of a particular named directory. If one is found within a subdirectory of the current folder, the environment is automatically activated. Once inside a virtual environment, that state is retained until you move out of the parent virtual environment directory, at which point the environment is deactivated.

    Place this inside your .bashrc or .bash_profile.

    function cd() {
      builtin cd "$@"
    
      if [[ -z "$VIRTUAL_ENV" ]] ; then
          # If config file is found -> activate the vitual environment
          venv_cfg_filepath=$(find . -maxdepth 2 -type f -name 'pyvenv.cfg' 2> /dev/null)
          if [[ -z "$venv_cfg_filepath" ]]; then
            return # no config file found
          fi
    
          venv_filepath=$(cut -d '/' -f -2 <<< ${venv_cfg_filepath})
          if [[ -d "$venv_filepath" ]] ; then
            source "${venv_filepath}"/bin/activate
          fi
      else
        # If the current directory is not contained 
        # within the venv parent directory -> deactivate the venv.
          cur_dir=$(pwd -P)
          venv_dir="$(dirname "$VIRTUAL_ENV")"
          if [[ "$cur_dir"/ != "$venv_dir"/* ]] ; then
            deactivate
          fi
      fi
    }
    

    Personally I think it's an improvement on a lot of the solutions here, since it should work for any virtual environment

提交回复
热议问题