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
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%
Latest comments (5)
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
Youβre right. It will deactivate.
Awesome! This is really useful for me. Do I just put the code in the
.zshrc
file?Yup, that's what I did.
Thanks!