Installing and Using pyenv on Ubuntu 22.04

pyenv is a convenient tool when you want to easily switch between and manage different versions of Python. This article explains how to install pyenv and its basic usage in an Ubuntu 22.04 environment.

Prerequisites

  • An environment with Ubuntu 22.04 installed
  • Basic knowledge of Linux command-line operations

目次

Installing Required Libraries

To use pyenv, you need to install the libraries required for building Python in advance.

sudo apt update
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 python3-openssl git

Installing pyenv

Installing from the GitHub Repository

Install pyenv from its GitHub repository.

git clone https://github.com/pyenv/pyenv.git ~/.pyenv

Configuring Environment Variables

To make pyenv available in your shell, configure your environment variables. Add the following to your ~/.bashrc or ~/.zshrc.

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

Run the following command to apply the changes.

source ~/.bashrc  # or source ~/.zshrc

Verifying the Installation

Verify that pyenv has been installed correctly using the following command.

pyenv --version

Installing and Managing Python

Checking Available Python Versions

You can check the available Python versions for installation with the following command.

pyenv install --list

Installing a Python Version

To install a specific version, use the following command.

pyenv install 3.13.1

To check the installed versions, run the following command.

pyenv versions

Switching Python Versions

Global (System-wide) Setting

To set the Python version used system-wide, run the following.

pyenv global 3.13.1

Local (Project-specific) Setting

To set a version used only within a specific directory, run the following.

pyenv local 3.13.1

Temporary Switching

To temporarily switch the version, run the following.

pyenv shell 3.13.1

Troubleshooting

If Python Fails to Build Correctly

Required dependencies may be missing. Recheck your dependencies using the following command.

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 python3-openssl git

If the PATH Setting is Incorrect

Recheck your environment variable settings and run source ~/.bashrc.


Conclusion

Using pyenv allows you to easily install and manage different versions of Python. This article introduced basic setup steps and commands, but please also refer to the official documentation for detailed usage and customization.

Official Website: pyenv GitHub