Mon, December 15, 2025 ยท 2 min read

How to setup python venv

How to setup python venv

System Python exists to keep the operating system alive. Your projects have no business touching it.

pyenv solves this by isolating Python versions cleanly, predictably, and without hacks.

Why pyenv Exists

Most breakage comes from three bad habits:

  • Modifying system Python
  • Mixing project dependencies
  • Relying on sudo pip

pyenv avoids all three by installing Python versions in user space and letting you choose which Python runs where.

Install pyenv

Linux (Debian / Ubuntu)

Install build dependencies first:

sudo apt update
sudo apt install -y \
  build-essential \
  curl \
  git \
  libssl-dev \
  zlib1g-dev \
  libbz2-dev \
  libreadline-dev \
  libsqlite3-dev \
  libffi-dev \
  liblzma-dev \
  tk-dev

Install pyenv:

curl https://pyenv.run | bash

Configure shell initialization (~/.bashrc or ~/.zshrc):

export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"

eval "$(pyenv init --path)"
eval "$(pyenv init -)"

Reload shell:

exec "$SHELL"

Verify:

pyenv --version

macOS (Homebrew)

brew install pyenv

Add to ~/.zshrc:

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

Install a Python Version

List available versions:

pyenv install --list

Install a specific version:

pyenv install 3.12.2

Set globally (default Python):

pyenv global 3.12.2

Or per project directory:

pyenv local 3.12.2

Install pyenv-virtualenv

git clone https://github.com/pyenv/pyenv-virtualenv.git \
  ~/.pyenv/plugins/pyenv-virtualenv

Enable it in your shell:

eval "$(pyenv virtualenv-init -)"

Create and Use a Virtual Environment

Create an environment tied to a specific Python version:

pyenv virtualenv 3.12.2 myenv

Activate it:

pyenv activate myenv

Bind the environment to the project directory:

pyenv local myenv

From now on, entering this directory automatically activates the environment.

Install pip Packages (Correctly)

Upgrade pip first:

pip install --upgrade pip

Install packages:

pip install requests flask

Verify installation:

pip list

Dependency Freezing

pip freeze > requirements.txt

Rebuild environment elsewhere:

pip install -r requirements.txt

Deactivate Environment

pyenv deactivate