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 likey to break it. Best practice is to use a clean virtual python environment for each application.
macOS
Brew can make this easy. Here is a very quick example of what you need:
brew install pyenv
pyenv versions #if you need to see what is availible
pyenv install 3.11.2
$HOME/.pyenv/versions/3.11.2/bin/python3 -m venv .env
source .env/bin/activate
Longer creation script with a shared folder:
This is a longer example where we use a shared location for the generated virtual envs.
#! /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"
##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}"
Written on August 20, 2024