Skip to content
Snell Rojas

Programming

Create Python Virtual Environments

How to create a Python virtual environment that uses a different Python version from your global one, with virtualenv and the deadsnakes PPA.

Snell RojasPublished Updated 2 min read

I wrote this post in Spanish in 2021 and adapted it to English in 2026.

Instructions for setting up a Python virtual environment that uses a different Python version from the one you have installed globally.

Example of when you'd need it: you have Python 3.8 installed, but you need to run scripts written in Python 2.7.

Solution: create a virtual environment with that Python version.

Steps:

First, install the Python version you need (in this guide you can see how I did it for Python 2.7, but you can follow the same steps for any Python version):

bash
$ sudo add-apt-repository ppa:deadsnakes/ppa # add the PPA
$ sudo apt install python2.7 # once the PPA is added, install Python

Now you need to install virtualenv. If you don't have it yet, you can install it with:

bash
$ sudo pip install virtualenv

Once it's installed, create the folder where you want the virtual environment (you can have a "master" folder with all your virtual environments, or create them inside the folders of the projects that need them; it all depends on how you organize yourself).

The syntax for creating a virtual environment with a specific Python version is:

bash
$ virtualenv --python=python_version virtual_env_name

In my case, I'm going to create a virtual environment with Python 2.7, and to find where its binary is, I ran this command:

bash
$ which python2.7
$ /usr/bin/python2.7

Now everything is ready to create the virtual environment with a specific Python version. Just type:

bash
$ virtualenv --python=/usr/bin/python2.7 p27

To activate the virtual environment, just type:

bash
$ source p27/bin/activate

Once it's active, you can check the Python version with:

bash
(p27)$ python --version
(p27)$ Python 2.7.18

To deactivate the virtual environment:

bash
(p27)$ deactivate

And that's it. All that's left is to start installing dependencies and whatever else is your business. See you, XOXOXO.