How to initialize multiple Python 3 virtual environments with each their own version of Python
Publish date: Apr 27, 2022
Introduction and constraints
Any serious tinkerer needs a handful of CPython versions on their environment, readily available. No? You poor bastard. Anyways…
The process assumes that you compile CPython yourself. You may also grab precompiled binaries, if you want to.
The whole process is based on Ubuntu 20.04 LTS, other distributions/OSes may have it differently.
The mechanism is based on the virtualenv
package: https://pypi.org/project/virtualenv/
virtualenv
assumes Python version 3.5+ (from the 3.x line), Ubuntu 20.04 contains version 3.8.
Install prerequisites for compiling CPython with all the properties you are likely to need:
sudo apt-get install libffi-dev libbz2-dev \
libssl-dev libz-dev libsqlite3-dev make
Compile CPython
- Clone the CPython source code from https://github.com/python/cpython and check out the version you want to build:
git checkout v3.10.3
- Configure it with appropriate install prefix (up to your taste and habits):
./configure --prefix=/home/user/.local/python3.10.4
- Make and install:
make -j9 install
Procedure of initializing virtual environments
- Install
pip
from the Ubuntu package:sudo apt-get install python3-pip
- Install the virtualenv in user mode:
python3 -m pip install --user virtualenv
- Create your virtual environment:
python3 virtualenv --python=/home/user/.local/python3.10.4/bin/python3 /home/user/venv-directory
- Activate your virtual environment:
. /home/user/venv-directory/bin/activate
- Done.