Python Version Management on WSL Ubuntu 20.04

January 9, 2024 | By Gerald | Filed in: Development and Programming.

In the world of Python development, having the flexibility to switch between different Python versions is crucial. This not only allows developers to stay up-to-date with the latest language features but also ensures compatibility with different projects.

In this blog post, we will explore two popular methods for managing Python versions on Ubuntu: update-alternatives and pyenv.

Using update-alternatives:

Step 1: Check available Python versions

Open a terminal and use the following command to view the available Python versions:

sudo update-alternatives --config python

Step 2: Switch Python versions

Select the desired Python version by entering the corresponding number and pressing Enter. Verify the switch by checking the Python version:

python --version

Using pyenv:

Step 1: Install pyenv

Install pyenv using the following commands:

git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PATH="$HOME/.pyenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init --path)"' >> ~/.bashrc
source ~/.bashrc

Step 2: Install the Desired Python Version

Use pyenv to install the Python version you need. For example, to install Python 3.11.0:

pyenv install 3.11.0

Step 3: Set the Global Python Version

Set the global Python version to the one you just installed:

pyenv global 3.11.0

Step 4: Verify the Switch

Check that the switch was successful by running:

python --version

You can also view a list of installed Python versions and their settings using:

pyenv versions

Using pyenv-virtualenv:

Step 1: Install pyenv-virtualenv plugin

Install the pyenv-virtualenv plugin to manage virtual environments:

git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv
export PATH="$HOME/.pyenv/plugins/pyenv-virtualenv/bin:$PATH"
eval "$(pyenv virtualenv-init -)"
source ~/.bashrc

Step 2: Create and activate a virtual environment

Create a virtual environment with the desired Python version:

pyenv virtualenv 3.11.0 myenv

Activate the virtual environment:

pyenv activate myenv

Step 3: Verify the Python version in the virtual environment

Ensure the correct Python version is active within the virtual environment:

python --version

Conclusion

Whether you prefer the system-wide approach of update-alternatives or the more flexible per-user and per-project management of Python versions with pyenv, these methods provide you with the tools needed to seamlessly switch between Python versions on your Ubuntu system. Choose the one that best fits your development workflow and project requirements. Happy coding!

SHARE THIS ARTICLE

Tags: , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *