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

后端 未结 12 2011
北海茫月
北海茫月 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条回答
  •  猫巷女王i
    2020-12-24 06:50

    This is my solution, which:

    • checks if already at the currently active venv, and do nothing in that case
    • if there is a venv folder, deactivate the active one if there is one
    • activate the new venv whatever if there was an old one or not.

    In my bash_aliases:

    function cd() {
        builtin cd "$@"
    
        if [ $(dirname "$VIRTUAL_ENV") == $(pwd) ] ; then
            # Already at the active virtual env
            return
        fi
    
        if [[ -d ./venv ]] ; then
            if type deactivate > /dev/null 2>&1 ; then
                printf "Deactivating virtualenv %s\n" "$VIRTUAL_ENV"
                deactivate
            fi
    
            source ./venv/bin/activate
            printf "Setting up   virtualenv %s\n" "$VIRTUAL_ENV"
        fi
    }
    

提交回复
热议问题