How To Automatically Activate Virtualenvs When Cd'ing Into A Directory

Asked one year ago
Answer 2
Viewed 348
-1

Put something like this in your .zshrc

function cd() {
  if [[ -d ./venv ]] ; then
    deactivate
  fi

  builtin cd $1

  if [[ -d ./venv ]] ; then
    . ./venv/bin/activate
  fi
}

Edit: As noted in comments 

cd

-ing into a subfolder of the current virtual env would deactivate it. One idea could be to deactivate the current env only if 

cd

-ing into a new one, like

function cd() {
  builtin cd $1

  if [[ -n "$VIRTUAL_ENV" && -d ./venv ]] ; then
    deactivate
    . ./venv/bin/activate
  fi
}

that could still be improved, maybe turning it into a "prompt command" or attempting some prefix matching on the folder names to check there's a virtual env somewhere up the path, but my shell-fu is not good enough.


Answered one year ago Naveen Ojha
0

You should try something like autoenv if not direnv.

The first one is considered to be "lightweight", while the second one "simply, higher quality software", listening respectively to each one's author, talking about the other one's project. Thus, they seem to me fairly good options, to try both!

Anyway, both have been tested on 

zsh

 shells. In particular, 

autoenv

 is really simple to use, after installing it:

$ git clone git://github.com/inishchith/autoenv.git ~/.autoenv
$ echo 'source ~/.autoenv/activate.sh' >> ~/.bashrc

just "follow the white rabbit " and try for example

$ mkdir project
$ echo "echo 'whoa'" > project/.env
$ cd project
whoa

"If a directory contains a 

.env

 file, it will automatically be executed when you 

cd

 into it. When enabled (set 

AUTOENV_ENABLE_LEAVE

 to a non-null string), if a directory contains a 

.env.leave

 file, it will automatically be executed when you leave it."

Have a look at https://github.com/inishchith/autoenv for more detailed instructions!...


Answered one year ago Anonymous