Skip to content

Instantly share code, notes, and snippets.

@kishannareshpal
Last active March 22, 2024 11:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kishannareshpal/342efc4a15e47ea5d338784d3e9a8d98 to your computer and use it in GitHub Desktop.
Save kishannareshpal/342efc4a15e47ea5d338784d3e9a8d98 to your computer and use it in GitHub Desktop.
Automatically activate python virtual environment when changing directory. In other words, it does `source ./venv/bin/activate` for you!

This is a custom shell script I wrote in order to ease my workflow when dealing with Python Virtual Environments.

Installation

Download the activatevenv.plugin.sh into your computer.

oh-my-zsh

  1. Download the script into $ZSH_CUSTOM/plugins/<plugin_name>/activatevenv/. See oh-my-zsh Plugin Customization Wiki
  # Use curl or download manually from https://git.io/JLBHr
  (mkdir activatevenv; cd activatevenv) && curl -L --url https://git.io/JLBHr --output ./activatevenv/activatevenv.plugin.zsh
  1. Edit your ~/.zshrc:
# Add activatevenv to your list of plugins and restart the terminal.
  plugins=(... , activatevenv)
  …

Manually

  1. Copy and paste the activatevend.plugin.sh script to the bottom of your ~/.bashrc or ~/.zshrc and restart your terminal.

Usage

Simply cd into a project directory with a python virtual environment setup (with any of these names: venv/, .venv/, env or .env), and the script will activate it automatically for you (just as you would do with source ./venv/bin/activate).

If you are creating a new virtualenv, run python -m <venv|virtualenv> <venv|.venv|.env|env> in your root directory and to activate it manually call activatevenv (also when you cd back into your project folder it will automatically activate it).

# Automatically activates venv if ./venv/ exists in curent directory
# Go to your project folder, run "pip virtualenv <.venv|venv>", so your project folder
# has a <.venv|venv> folder at the top level
# .
# ├── <other_project_files>
# ├── ...
# └── <.venv|venv|.env|env>
# ├── bin
# ├── include
# └── lib
#
# The virtualenv will be activated automatically when you enter the directory.
# To deactivate run `deactivate` and to manually activate run `activatevenv`
function activatevenv() {
# Names of possible virtualenv directories
VIRTUALENV_DIRS=("venv/" "env/" ".env/" ".venv/" "${PWD##*/}")
for dir in $VIRTUALENV_DIRS; do
if [[ -d "${dir}" ]]; then
# Found a possible venv directory
# Try activating the venv
if [[ -e "./${dir}/bin/activate" ]]; then
source ./$dir/bin/activate
echo "Virtual environment activated automatically"
break
fi
fi
done
}
activatevenv
# Extension for `cd` command in order to automatically activate virtualenv when changin directories.
function cd() {
builtin cd $1
# Try activating venv
activatevenv
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment