Creating Python development environments on Linux/macOS using pyenv and venv

Introduction

When using Python it is important to not use the default OS Python. If you are starting out it will seem to work fine initially, but down the road you are VERY likey to break it. Best practice is to use a clean virtual python environment for each application. Good news, this post will walk you through it on both Linux and macOS.

Using 3.8.1 here, but use any version of Python you wish if it doubt use the latest stable as listed on the python site link

##Linux: Download and Build:

#! /bin/bash
PYTHON_VERSION="3.10.3"
PYTHON_EXEC="python3.10"
PYTHON_DIR="$HOME/.runtimes/Python310"
PYENV_DIR="$HOME/.pyenv"

#Install Git
sudo yum install -y git

# Install build dependencies
sudo yum install gcc zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel libffi-devel
git clone https://github.com/pyenv/pyenv.git $PYENV_DIR

${PYENV_DIR}/plugins/python-build/bin/python-build ${PYTHON_VERSION} ${PYTHON_DIR}

echo "Python runtime is available at ${PYTHON_DIR}/bin/${PYTHON_EXEC}"

macOS Python download and build

Good news, brew makes it very easy

brew install pyenv
pyenv install 3.10.3

Create a Virtual Env:

Now you have a specific Python Env, you can use venv to create a virtual environment from it:

#! /bin/bash
PROJECT_NAME="project_name" # CHANGE THIS VAR TO WHATEVER PROJECT NAME
VIRTUALENVS_DIR="$HOME/.virtualenvs"

PYTHON_EXEC="python3"
# Linux PYTHON_DIR="$HOME/.runtimes/Python38"
PYTHON_DIR="$HOME/.pyenv/versions/3.10.3"
PYENV_DIR="$HOME/.pyenv"

# Create the virtual environment
${PYTHON_DIR}/bin/${PYTHON_EXEC} -m venv ${VIRTUALENVS_DIR}/${PROJECT_NAME}
# Activate the virtual environment
source ${VIRTUALENVS_DIR}/${PROJECT_NAME}/bin/activate

# Print python version and location :)
which python
python --version

echo "Every time you need to work on this project please remember to use this interpreter"
echo "If you are using VSCode or Pycharm, set the path "$(which python)" as your interpreter location"
echo "source ${VIRTUALENVS_DIR}/${PROJECT_NAME}/bin/activate"

If you want to just keep it breif:

python3 -m venv .env
source .env/bin/activate

That is it, remember to use the virtual env for your project and create new virtual environments for each project.

Written on February 21, 2022