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%
edit2: been trying out fish shell. Here it is translated to fish script:
function python_venv --on-variable PWD
set myvenv ./venv
if test -d $myvenv
source $myvenv/bin/activate.fish
else if type -q deactivate
deactivate
end
end
Oldest comments (6)
Awesome! This is really useful for me. Do I just put the code in the
.zshrcfile?Yup, that's what I did.
Thanks!
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.
Thank you so much!! This is exactly what I was looking for :D