2 min read

Creating Python Virtual Environments with venv on macOS Tahoe

venv is a built-in module in Python 3 for creating lightweight "virtual environments". Each virtual environment has its own independent set of installed Python packages, allowing you to isolate project dependencies. This prevents conflicts between different projects that might require different versions of the same package.

Prerequisites

  • Python 3.3 or later must be installed on your system. macOS Tahoe comes with Python pre-installed, but it is often an older version. It's recommended to install a newer version using Miniconda or Homebrew.

Creating a Virtual Environment

  1. Open your terminal and navigate to your project directory (or create one).

  2. Run the following command:

    python3 -m venv .venv
    • python3: Specifies the Python 3 executable.
    • -m venv: Tells Python to run the venv module.
    • .venv: The name of the virtual environment directory. It's common to name it .venv to keep it hidden and out of the way.

Activating the Virtual Environment

Before you can use the virtual environment, you need to activate it. This modifies your shell's PATH to use the Python executable and packages within the environment.

source .venv/bin/activate

Your terminal prompt will change to indicate that the environment is active (e.g., (.venv) $).

Installing Packages

With the virtual environment activated, you can install packages using pip:

pip install requests pandas numpy

These packages will be installed only within the virtual environment, not globally on your system.

Deactivating the Virtual Environment

When you are finished working on the project, deactivate the environment:

deactivate

Your terminal prompt will return to normal.

  • Installing Python in User Space with Miniconda on macOS Tahoe
  • Pip (Installing packages without sudo)