Creating and Managing Python Virtual Environments on Ubuntu 20.04

About Virtual Environments

A python virtual environment is a self-contained directory tree that includes a Python installation and number of additional packages.

The main purpose of Python virtual environments is to create an isolated environment for different Python projects. This way you can install a specific version of a module on a per-project basis without worrying that it will affect your other Python projects.

Initial Setup

Ubuntu 20.04 ships with Python 3.8 by default. You can verify that Python 3 is installed on your system by running:

python3 -V

The output should look like this:

Python 3.8.5

Starting from Python 3.6, the recommended way to create a virtual environment is to use the venv module.

We must install the python3-venv package that provides the venv module.

sudo apt install python3-venv

Once the module is installed, we are ready to create virtual environments for Python 3.

Creating a Virtual Environment

Switch to the directory where you would like to store your Python 3 virtual environments. Within the directory run the following command to create your new virtual environment:

python3 -m venv my-project-env

The command above creates a directory called my-project-env, which contains a copy of the Python binary, the Pip package manager, the standard Python library and other supporting files.

Using a Virtual Environment

To start using this virtual environment, you need to activate it by running the activate script:

source my-project-env/bin/activate

Once activated, the virtual environment’s bin directory will be added at the beginning of the $PATH variable. Also your shell’s prompt will change and it will show the name of the virtual environment you’re currently using. In our case that is “my-project-env”:

$ source my-project-env/bin/activate
(my-project-env) $

Now that the virtual environment is activated, we can start installing, upgrading, and removing packages using pip.

Once you are done with your work to deactivate the environment, simply type deactivate and you will return to your normal shell.

(my-project-env) $ deactivate

Creating a Requirements File

It is often very helpful to create a requirements file containing all of the pip packages and their versions you are using in a particular virtual environment. This can enable you to quickly setup a brand new environment on another development or production machine.

To generate a requirements file, run the following command while your virtual environment is activated:

(my-project-env) $ pip freeze > requirements.txt

This uses the freeze command in pip to output all installed packages in requirements format, then saves the output into a file named requirements.txt.

In order to install packages into a new virtual environment from a requirements file, run the following command:

(new-project-env) $ pip install -r requirements.txt