Dev Notes

Software Development Resources by David Egan.

Virtualenv & Virtualenvwrapper Setup in Python 3 on Ubuntu Focal Fossa


Python
David Egan

This article outlines Virtualenv and Virtualenvwrapper installation on Python 3 on Ubuntu.

A virtual environment in Python is an isolated working copy of Python and associated modules that allows you to work on a specific project without fear of affecting other projects or your system as a whole.

Virtualenv

virtualenv creates a folder which holds all the necessary modules for a project.

A new virtual environment is created by:

cd project_directory
virtualenv my_project

You could also keep all virtual environments in one directory, and activate your environment by referencing this.

An environment is started by sourcing a file bin/activate located in the isolated environment. For example:

. /path_to_environments/my_project/bin/activate

This changes your prompt to reflect the virtual environment - in this case: (my_project).

Once you have used pip to install modules within the environment, you can easily reproduce the specific context by creating a requirements.txt manifest file with the pip freeze command:

pip freeze > requirements.txt

You can add this file into version control, and use it to set up a new virtualenv as required:

# Set up a new virtualenv
# Install dependencies in the requirements.txt
pip install -r requirements.txt

Install Virtualenv

Install pip3 if necessary:

sudo apt install python3-pip

Add an alias for the pip3 command. Add to .bashrc if you want to make this permanent:

alias pip='pip3'

Install Virtualenv:

pip install virtualenv

Virtualenvwrapper

virtualenvwrapper is a set of shell functions that serve as extensions tovirtualenv.

The extensions include wrappers for creating and deleting virtual environments and otherwise managing your development workflow, making it easier to work on more than one project at a time without introducing conflicts in their dependencies.

Install Virtualenvwrapper

pip install virtualenvwrapper

Add the following to .bashrc or .profile:

# Next line not necessary unless you want to specify a different location - ~/.virtualenvs is the default
export WORKON_HOME=$HOME/.virtualenvs

# $PROJECT_HOME tells virtualenvwrapper where to place project working directories.
# This is required for the `mkproject` command.
export PROJECT_HOME=$HOME/Devel

# Source the script, making functions available in the shell
source /usr/local/bin/virtualenvwrapper.sh

Virtualenvwrapper Quickstart

  1. Run workon: display a list of environments (which will be empty on first run)
  2. Run: mkvirtualenv temp: a new environment temp is created and activated
  3. Run: workon: the new temp environment is included
  4. deactivate to return to the system installed Python

References


comments powered by Disqus