Skip to Content

Managing Python virtual environments

Installation

# macOS
brew install python3 python-pip

# Ubuntu
sudo apt install python3 python-pip

# Update pip to the latest version
pip install --upgrade pip setuptools wheel
pip3 install --upgrade pip setuptools wheel

# Install virtualenvwrapper
pip3 install virtualenv virtualenvwrapper

Create projects directory

mkdir ~/Projects

Configure .profile (Bash) or .zprofile (ZSH):

# needed for virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Projects
export VIRTUALENVWRAPPER_PYTHON=/bi/home/USER/.linuxbrew/bin/python3
export VIRTUALENVWRAPPER_VIRTUALENV=/bi/home/USER/.linuxbrew/bin/virtualenv
export PIP_REQUIRE_VIRTUALENV=true
source /bi/home/USER/.linuxbrew/bin/virtualenvwrapper.sh

Reload profile

source ~/.profile
source ~/.zprofile

Make a new project

  • The command will create a python virtual environment by running mkvirtualenv.
  • Then it will creates a project directory and will turn to that directory.
# using the default python version
mkproject projectName

# using specific python version
mkproject -p `which python` projectName

To delete a project

rmvirtualenv projectName

Bonus

If you are using ZSH shell with prezto (recommended), you can change prezto prompt to indicate the virtual environment currently in use. You need to edit prompt_sorin_setup as follow1 :

cd $HOME/.zprezto/modules/prompt/functions/
# Check for activated virtualenv
if (( $+functions[python-info] )); then
python-info
fi

# Compute slow commands in the background.
     'status' '$(coalesce "%b" "%p" "%c")%s%A%B%S%a%d%m%r%U%u'
     
# %v - virtualenv name.
zstyle ':prezto:module:python:info:virtualenv' format '(%v)'

# Define prompts.
PROMPT='${SSH_TTY:+"%F{9}%n%f%F{7}@%f%F{3}%m%f "}%F{4}$python_info[virtualenv] ${_prompt_sorin_pwd}%(!. %B%F{1}#%f%b.)${editor_info[keymap]} '

[1] How to display current virtualenv in your ZSH Prezto theme