In this article, we’ll discuss how to manage multiple Python versions on a Linux system. Managing multiple versions of Python can be useful for testing compatibility with different versions of libraries, or for running applications that require a specific version of Python. We’ll cover how to install and manage different versions of Python using the apt
package manager and the pyenv
tool.
Installing Python Versions with apt
The apt
package manager is used to install system-wide packages on Debian-based Linux distributions. It can be used to install different versions of Python by installing the corresponding pythonX.Y
package. For example, to install Python 3.9, we can run:
sudo apt install python3.9
Similarly, to install Python 2.7, we can run:
sudo apt install python2.7
After installing a new version of Python with apt
, it can be used by running the pythonX.Y
command. For example, to start a Python 3.9 interpreter, we can run:
python3.9
Installing pyenv
pyenv
is a popular tool for managing multiple Python versions on a Linux system. It allows us to easily install and switch between different versions of Python without affecting the system-wide Python installation.
To install pyenv
, we first need to install some dependencies. On Ubuntu and Debian-based systems, we can install these dependencies with the following command:
sudo apt install git curl make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev
Once the dependencies are installed, we can clone the pyenv
repository and add it to our shell’s environment:
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init --path)"' >> ~/.bashrc
After adding pyenv
to our shell’s environment, we can install different versions of Python using the pyenv install
command. For example, to install Python 3.9, we can run:
pyenv install 3.9.5
Similarly, to install Python 2.7, we can run:
pyenv install 2.7.18
Once a version of Python is installed with pyenv
, we can switch to it using the pyenv global
command. For example, to switch to Python 3.9, we can run:
pyenv global 3.9.5
After switching to a new version of Python, we can verify that it’s being used by running the python
command:
python --version
Conclusion
In this article, we’ve discussed how to manage multiple Python versions on a Linux system. We’ve covered how to install different versions of Python using the apt
package manager, as well as how to install and use the pyenv
tool. By managing multiple Python versions, we can test compatibility with different versions of libraries and run applications that require a specific version of Python.