How to use Python venv to manage multiple Python versions
Python is a great language for quick and intuitive programming, but the entire Python ecosystem as a whole can be extremely frustrating. There are a few methods for managing multiple Python versions, but ‘venv’ is included with Python and, IMO, provides perhaps the simplest way to manage a Python environment in that it can be set up directly in a project directory.
Installing Multiple Python Versions
I prefer to have all my Python versions installed under a hidden subdirectory of my home directory such as
$HOME/.local.`hostname`
When I need a new version of Python, I download the source code and compile it with:
$ ./configure --prefix=$HOME/.local.`hostname`
$ make -j8 && make install
This path does not need to be directly added to you environment variables, venv takes care of that.
Setting up a venv
For packages that requires specific versions of python, you call ‘python venv’ directly from your new install location:
$ cd /path/to/project
$ $HOME/.local.`hostname`/bin/python3.10 -m venv venv
$ . venv/bin/activate
$ pip install -r requirements.txt
The activate command needs to be run each time you use the software, but it can be automated in a script:
#!/bin/bash
. venv/bin/activate
python project.py
deactivate