Pyenv and virtualenv setup

Setup pyenv

First you have to download the packages that pyenv will need later to install different Python versions and the pyenv itself has to be installed.

$ sudo apt update

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

$ curl -fsSL https://pyenv.run | bash

In order to be able to use pyenv in the shell, put the shell initialization code into the .bashrc or .zshrc file depending on the shell you use.

export PYENV_ROOT="$HOME/.pyenv"
[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init - bash)"
eval "$(pyenv virtualenv-init -)"

Create a virtual environment

You can list all available Python versions that can be installed.

$ pyenv install -l

As an example the Python version 3.13.7 is being installed. This version differs from the current Python version delivered in Ubuntu but this is the one that is supported for AWS Lambda Functions. The -s flags skip the installation if the specified version is already installed.

$ pyenv install -s 3.13.7

To list all the exisiting environments the versions command can be used.

$ pyenv versions

Create a virtual environment called myenv that uses the Python version 3.13.7.

$ pyenv virtualenv 3.13.7 myenv

Activating a virtual environment

Navigate to your project folder and activate the environment. Every time you navigate into this folder the environment will get activated and when you leave the folder it will get deactivated. Note that a new file ‘.python-version’ will be created to support the automatic activation. Of course pyenv virtualenv has to be properly configured in order to have this running.

$ cd ~/projects/myapp
$ pyenv local myenv

You can manually activate or deactivate any environments.

$ pyenv activate myenv
$ pyenv deactivate

Note, that the environments are independent from each other; they can use different Python version and different set of Python packages. It is recommended to make a separate environment for each project.