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?
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?
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.
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.
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.
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
apt
stuff is specific to Debian and derivatives; this is very platform-specific advice even in the absence of the undeclared third-party dependency. –
Quantitative © 2022 - 2024 — McMap. All rights reserved.