18

Auto activate and deactivate python venv using zsh

 2 years ago
source link: https://dev.to/moniquelive/auto-activate-and-deactivate-python-venv-using-zsh-4dlm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cover image for Auto activate and deactivate python venv using zsh
Cyber

Posted on Dec 17

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
  # 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%


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK