Create a Python Virtual Environment on Ubuntu 16.10

Updated by Linode Contributed by Christopher Piccini

Contribute on GitHub

View Project | View File | Edit File

Create a Python Virtual Environment on Ubuntu 16.10

What is a Python Virtual Environment?

A Python Virtual Environment - or virtualenv - is a tool to create an isolated Python environment on your Linode. This can be extremely powerful as you can create a virtual environment and install all Python executables/packages to it, leaving no dependencies outside of your created virtual environment.

The purpose of this tutorial is to allow you to create and run Python virtual environments in your Ubuntu 16.10 Linode.

Before You Begin

  1. This guide will use sudo wherever possible. Complete the sections of our Securing Your Server to create a standard user account, harden SSH access and remove unnecessary network services.

  2. Update your system:

    1
    sudo apt update
    

Install Python Virtualenv

  1. To install Python’s virtual environment:

    1
    sudo apt install virtualenv
    

Create New Directory in Home

  1. Navigate to your users home directory:

    1
    cd
    
  2. Create a directory named python-environments:

    1
    mkdir python-environments
    
  3. Navigate in the newly created directory:

    1
    cd python-environments
    

Create a Virtual Environment in Python 3

  1. Create a virtual environment in Python 3 with the environment name of env:

    1
    virtualenv -p python3 env
    
  2. Validate that environment is installed with python3:

    1
    ls env/lib
    

Activate Environment

  1. Activate the newly created virtual environment (the name of the working environment will appear in parentheses):

    1
    2
    source env/bin/activate
    (env) testuser@localhost:~/python-environments$
    

    Now that the environment is active, you can install executables and packages only to this virtual environment.

Deactivate Environment

To deactivate an active virtual environment:

1
    deactivate

Congratulations! You have created an isolated, Python Virtualenv on your Linode.

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This guide is published under a CC BY-ND 4.0 license.