DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Auto activate and deactivate python venv using zsh
Cyber
Cyber

Posted on • Updated on

Auto activate and deactivate python venv using zsh

When I found out about python venv (apt-get install python3-venv) I became an instant addict. It's clean, it's built-in and it's explicit.

Now every time I create a new project folder I automatically run python3 -mvenv venv && source ./venv/bin/activate.

But typing ./venv/bin/activate and then deactivate is too much work for my lazy programmer head.

So I decided to finally invest 10 minutes to free me from activating and deactivating python's env every time I enter or leave a folder with my standard ./venv folder:

#---------------------------------------------- chpwd pyvenv ---
python_venv() {
  MYVENV=./venv
  # when you cd into a folder that contains $MYVENV
  [[ -d $MYVENV ]] && source $MYVENV/bin/activate > /dev/null 2>&1
  # when you cd into a folder that doesn't
  [[ ! -d $MYVENV ]] && deactivate > /dev/null 2>&1
}
autoload -U add-zsh-hook
add-zsh-hook chpwd python_venv

python_venv
Enter fullscreen mode Exit fullscreen mode

edit: just figured out that deactivating was working because of other stuff installed in my shell. Now it's a bit more agressive but works 100%

Top comments (5)

Collapse
 
dillonb07 profile image
Dillon Barnes

Awesome! This is really useful for me. Do I just put the code in the .zshrc file?

Collapse
 
moniquelive profile image
Cyber

Yup, that's what I did.

Collapse
 
dillonb07 profile image
Dillon Barnes

Thanks!

Collapse
 
alimehr75 profile image
Alimehr75

so what should we do when a parrent directory has venv but child ones dosnt ?
when im in project dir that has venv its okay but when cd to child dir it deactivates the venv

Collapse
 
moniquelive profile image
Cyber

You’re right. It will deactivate.

New programmer and javascript

Stop by this week's meme thread!