'How to create python 2.7 virtual environment using python 3.7

I have Python 3.7 && I would like to create a python 2.7 virtual environment to run some code that only works on python 2.7

How do I create this python 2.7 virtual environment?

python3 -m venv ?



Solution 1:[1]

When creating virtual environment, a pyvenv.cfg is created that has home key which tells where the python executable is, which was used to create the virtual environment. If your global python installation is version 3.8.6, and you run

python3 -m venv something

you will create virtual environment in folder something, that has pyvenv.cfg that points to the python executable of the Python 3.8.6 installation. There is no easy way* to make it point to the Python 2.7 executable.

What can you do?

virtualenv as venv replacement

The venv module was introduced in Python 3.3, so you cannot use it to create virtual environments with python 2.7. You could use the virtualenv package which is a superset of venv. First, install it with python 2.7**:

python -m pip install virtualenv

If Python 2.7 is not on your PATH as python, use full path to the python executable in place of python. Then, you can create virtual environments that have Python 2.7 with

virtualenv something

or

virtualenv --python=python2.7 something 

* It is not supported by the venv module out of the box, at least.
** You can actually install it with any Python version, but then you will have to specify --python=/opt/python-2.7/bin/python or --python=python2.7 when running virtualenv. By default, it uses the python executable that was used to install it.

Solution 2:[2]

venv doesn’t allow creating virtual environments with other versions of Python than the one currently installed. You would have to use the traditional virtualenv package which allows creating virtual environments for different versions of python by providing the path to the binary like this:

virtualenv --python=/usr/bin/python2.7 /path/to/virtualenv/

where the path /usr/bin/python2.7 refers to the path of the binary for Python 2.7 on your system.

Solution 3:[3]

Install python2.7

Add universe repo

sudo apt-add-repository universe

sudo apt update

Install python2.7

sudo apt install python2-minimal

Create virtualenv with python2.7

mkvirtualenv -p $(which python2) something

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 np8
Solution 2 Jarvis
Solution 3 Nahum Trinidad Venancio