Skip to Content

Managing Python virtual environments

Installation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 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

1
mkdir ~/Projects

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

1
2
3
4
5
6
7
# 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

1
2
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.
1
2
3
4
5
# using the default python version
mkproject projectName

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

To delete a project

1
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 :

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

# Compute slow commands in the background.
1
2
3
4
5
6
7
8
     '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