If you are new to programming in Python, you might find it tricky to manage different versions of Python on your computer. This is where PyENV comes in handy. PyENV is a powerful tool that helps you switch between different versions of Python easily. Whether you’re working on an old project that needs Python 2.7 or a new one that requires Python 3.12, PyENV can make your life much easier.

In this guide, we will walk you through the process of installing and setting up PyENV on an Ubuntu system. Don’t worry if you’re not very experienced with Linux or Python. We will keep everything simple and straightforward, so you can follow along without any problems. By the end of this guide, you’ll be able to install any version of Python you need and switch between them effortlessly.

Step 1: Update Your System

First, you need to make sure your Ubuntu system is up to date. Open your terminal and type the following commands:

sudo apt update
sudo apt upgrade

These commands will update the list of available packages and their versions, and install newer versions of the packages you have.

Step 2: Install Prerequisites

PyENV needs some dependencies to work correctly. Install them by running:

sudo apt install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl git

This command installs all the necessary packages that PyENV requires.

Step 3: Install PyENV

Next, you need to install PyENV. The easiest way to do this is by using the Git version control system. Run the following commands in your terminal:

curl https://pyenv.run | bash

This script will install PyENV and set it up for you.

Step 4: Update Your Shell Configuration

After installing PyENV, you need to add it to your shell configuration so that it loads every time you open a terminal. You can do this by adding the following lines to your ~/.bashrc file:


export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

To apply these changes, run:

source ~/.bashrc

Step 5: Install Python Versions

Now that PyENV is set up, you can install any version of Python you need. For example, to install Python 3.9.6, run:

pyenv install 3.9.6

You can list all available Python versions with:

pyenv install --list

Step 6: Set a Global Python Version

You can set a global Python version that will be used by default. To set Python 3.9.6 as the global version, run:

pyenv global 3.9.6

You can check the current global Python version with:

pyenv version

Conclusion

Congratulations! You have successfully installed and set up PyENV on your Ubuntu system. Now, you can easily manage multiple Python versions and switch between them as needed. This will make your Python development much more flexible and efficient. If you encounter any issues, remember to check the PyENV documentation and community for help.