Setting up Python virtual environments

Published: June 20, 2022

In this post, you'll learn how to set up virtual environments for Python. Virtual environments help you isolate your project dependencies from each other and system-level packages.

Table of contents

Python versions

In most Linux distributions, python3 comes pre-installed. Check if it's installed using the command,

python3 --version
# prints Python 3.x.x


PIP is the package manager for python, similar to APT for debian/ubuntu distros.

Install PIP using the command,

sudo apt install python3-pip

pip3 --version

Virtual environments

virtualenv is a python tool that allows you to create and use virtual environments. virtualenvwrapper is another python tool that helps you to organise and manage multiple virtual environments from one place. Using virtualenv-wrapper is a best practice as it stores all environments in one place (within your home folder) and avoids clutter.

Install virtualenv and virtualenvwrapper

sudo pip3 install virtualenv
sudo apt-get install python3-setuptools
sudo pip3 install wheel

pip3 install virtualenvwrapper

Add the following lines to ~/.zshrc file.

# virtualenvwrapper config
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source $HOME/.local/bin/

Save and exit.

Before loading these configurations, understand what the above lines do.

  • Sets the folder $HOME/.virtualenvs as WORKON_HOME, i.e., default place to store all your virtual environments. Note that, any file or folder starting with a dot(.) is hidden in Linux.
  • Sets the folder $HOME/Dev as PROJECT_HOME, i.e., default place to create projects using the mkproject command.
  • Configure virtualenv to always use python3.
  • Loading the script. The contents of this shell script is beyond the scope of this post.

Finally reload the shell config file for changes to take effect.

source ~/.zshrc

Creating a virtual environment

To create a virtual environment, use the command,

# syntax: mkvirtualenv <venv_name>
mkvirtualenv myfirstvenv

You can see the new environment is created and activated immediately. The active virtual-environment 's name is displayed in your shell prompt.

When a virtual-environment is active, any PIP packages you install will remain specific to that environment. Watch the video at the end of this post to understand this better.

Deactivating a virtual environment

To deactivate a virtual environment, simply issue the command deactivate. You should the name of virtual environment disappear from your shell prompt.

To activate the environment again,

# syntax: workon <venv_name>
workon myfirstvenv


Last updated: June 20, 2022, 7:06 p.m.