Creating a Virtual Environment for Python on Ubuntu 16.04

Reading Time: 2 minutes

Virtualenv is a tool that creates an isolated environment separate from other projects. In this instance we will be installing different Python versions, including their dependencies.  Creating a virtual environment allows us to work on a Python project without affecting other projects that also use Python. It will utilize Python’s core files on the global environment to run, thus saving you disk space while providing the freedom to use different Python version for separate apps.

Pre-flight

  • Pip installation is required this will install Python at the same time.
  • Logged in as root or a user with admin privileges on an Ubuntu 16.04 LTS server. If logged in with a regular user with admin privileges be sure to use sudo before the commands discussed within this tutorial.

Step 1: Install Virtualenv

First, we will update our apt-get, then we will install the module virtualenv module.

apt-get update

apt-get install python-virtualenv

Step 2: Create a Virtual Environment & Install Python 3

Virtualenv works by creating a folder that houses the necessary Python executables in the bin directory. In this instance, we are installing Python 3.5 while also creating two folders, the virtualenvironment, and project_1 directory.

virtualenv -p /usr/bin/python3 virtualenvironment/project_1

Virtualenv will create the necessary directories into the project_1 directory. In this directory you’ll find bin, include, lib, local and share.

Step 3: Activate Your Virtual Environment

Navigate to the project_1/bin directory and activate your new environment from within that folder by using the source command below. Anytime you need to work on your project you will need to enable with:
cd virtualenvironment/project_1/bin

source activate

Or if you are outside of the bin directory, you can use

$ source virtualenvironment/project_1/bin/activate

You’ll see that you are now in this newly made environment by the change of the shell prompt reflecting the name created in Step 2.
(project_1) root@host2:~#When Python packages are installed, they will live in the lib directory, project_1/lib/python3.5/site-packages.

Exit your virtual environment by typing:
deactivate

 

Author Bio

About the Author: Echo Diaz

Throughout Echo's four year stint as a technical support specialist, her passion for breaking down complex concepts has to lead to a career in professional writing. As a top tier support specialist, she adds a distinctive element to her written work that speaks to customer feedback and concerns.

Echo occasionally pops her head out from behind her computer to watch her dog energetically run around the yard and unabashedly shovels money into buying tickets to see her favorite musical artists.

Refer a friend and receive hosting credit