How to Install Pyenv on Ubuntu 18.04
If you’re working with multiple Python projects, each requiring a different Python version, Pyenv makes it easy to install and switch between them. In this guide, we’ll walk through the process of installing and setting up Pyenv on Ubuntu 18.04.
Step 1: Update and Upgrade the System
To start, update the package list and upgrade existing packages to make sure everything is up to date.
Step 2: Install Dependencies
Pyenv requires several dependencies to compile and manage different Python versions. Install these by running:
Step 3: Install Pyenv
You can now download and install Pyenv. The simplest way to install it is through the Pyenv installer script.
- Download and run the installer script:
This will install pyenv, pyenv-virtualenv, and pyenv-update, giving you tools for managing Python versions, creating virtual environments, and updating Pyenv.
- Add Pyenv to your shell’s configuration:
After installation, you need to add Pyenv to your shell so it loads each time you start a terminal. Open the shell configuration file (for example,
for Bash users):~/.bashrc
Add the following lines to the end of the file:
- Apply the changes by restarting your terminal or running:
Step 4: Verify Pyenv Installation
To make sure Pyenv is correctly installed, use the following command:
You should see the version number if the installation was successful.
Step 5: Installing a Python Version
With Pyenv installed, you can now install a specific version of Python. For example, to install Python 3.8.12:
You can list available versions by running:
This will show all Python versions that Pyenv can install, including stable releases and development versions.
Step 6: Setting the Default Python Version
Once you have installed your desired Python version, you can set it as the global default:
This command sets Python 3.8.12 as the default version, which will be used whenever you open a terminal. To confirm the version:
You can also set the Python version on a per-project basis. Navigate to the project directory and use:
This creates a
.python-version
Step 7: Managing Virtual Environments with Pyenv
If you installed the Pyenv installer script in Step 3, you already have pyenv-virtualenv, which allows you to create isolated environments.
- Create a virtual environment by running:
Replace
with a name for your environment.myenv
- Activate the virtual environment:
- Deactivate it by simply running:
To delete an environment, use:
Summary
You’ve successfully installed Pyenv on Ubuntu 18.04 and configured it to manage multiple Python versions. You can now seamlessly switch between versions and create isolated virtual environments for each project.