How to Manage Python Versions on WSL Ubuntu

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 guide, we will explore two popular methods for managing Python versions on Ubuntu: update-alternatives and pyenv.

Method 1: 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

Method 2: 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

Final Step: 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

Optional: Using pyenv-virtualenv

The pyenv-virtualenv is an optional extension to pyenv that provides additional functionality for managing virtual environments.

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

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

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!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.