How to install Python using pyenv on Ubuntu
1. Objective:
This procedure outlines the steps to install pyenv
and use it to manage and install a
specific version of Python on an Ubuntu system with sudo privileges.
2. Steps:
Step 1: Update and Install Prerequisites
Run the following commands to ensure your system is up-to-date and has the necessary dependencies for building Python:
sudo apt update && sudo apt upgrade -y
sudo apt install -y make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev \
libffi-dev liblzma-dev git
Step 2: Install pyenv
Download and install pyenv using the official installer script:
curl https://pyenv.run | bash
Step 3: Configure Shell for pyenv
Add the following lines to your shell profile to enable pyenv. The file to modify depends on your shell:
- For bash, modify ~/.bashrc:
echo -e '\n# Pyenv Configuration\nexport PATH="$HOME/.pyenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init --path)"' >> ~/.bashrc
echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc
source ~/.bashrc
- For zsh, modify ~/.zshrc:
echo -e '\n# Pyenv Configuration\nexport PATH="$HOME/.pyenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init --path)"' >> ~/.zshrc
echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.zshrc
source ~/.zshrc
Step 4: Verify pyenv Installation
Check that pyenv is correctly installed by running:
pyenv --version
Step 5: Install the Desired Python Version
Use pyenv to install your desired Python version, replacing
pyenv install <version>
Step 6: Set the Installed Version as Default
Set the newly installed Python version as the global default:
pyenv global <version>
Verify that the correct version is being used:
python --version
Step 7: (Optional) Install Virtualenv Plugin
It is recommended that you manage the virtual environments using the virtualenv installed with the Python version you are using. Then, you can create a virtual environment using the following command:
python -m venv myenv
Alternatively however, to manage virtual environments more effectively, you can install the pyenv-virtualenv plugin:
git clone https://github.com/pyenv/pyenv-virtualenv.git
~/.pyenv/plugins/pyenv-virtualenv
Reload your shell configuration and verify the plugin is active:
source ~/.bashrc # or ~/.zshrc pyenv virtualenv --version
3. Additional Information:
Ensure that your system has sufficient storage and memory to compile Python from source.
If you encounter build errors, check the pyenv wiki for common build problems. To
uninstall a Python version, use pyenv uninstall