Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Python 2.7 virtual environment using Python 3.7

I have Python 3.7 but 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

Like this?

like image 965
Wang-Zhao-Liu Q Avatar asked Sep 06 '25 03:09

Wang-Zhao-Liu Q


2 Answers

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.

like image 72
np8 Avatar answered Sep 10 '25 11:09

np8


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.

like image 29
Jarvis Avatar answered Sep 10 '25 10:09

Jarvis