liveBook · Manning

Venv module

As explained in Road to Kubernetes

venv is a Python standard-library module for creating and managing virtual environments.

Python projects can need different versions of third-party packages. The built-in venv module creates a virtual environment for each project, keeping its packages organized and helping avoid version conflicts. A virtual environment is not complete isolation. section 2.1.1

To set up a FastAPI project:

  • Create a project folder, navigate into it, and run python3 -m venv venv on macOS or Linux, or python -m venv venv on Windows. The new venv directory holds the environment. section 2.1.1
  • Activate it with source venv/bin/activate on macOS or Linux, or .\venv\Scripts\activate on Windows. Activate it again whenever you return to work on the project; an editor may do this for you. section 2.1.1
  • Install dependencies into the activated environment with python -m pip install fastapi, or install the project's package list with python -m pip install -r src/requirements.txt. section 2.1.1
Listing 2.2 Creating a Python virtual environment
# In our Python project folder
cd ~/Dev/roadtok8s/py/

# Windows users
python -m venv venv

# Linux or macOS users
python3 -m venv venv

The command runs venv through the chosen Python interpreter; the final venv names the directory to create. section 2.1.1

On an Ubuntu server, install python3-venv if the venv module is unavailable, then create a server-side environment with python3 -m venv /opt/venv/. Deployment commands can use /opt/venv/bin/python directly to install requirements without first activating the environment. section 3.4.1

Listing 3.18 Installing Python packages with absolute paths
/opt/venv/bin/python -m pip install -r \
    /opt/venv/roadtok8s/py/src/requirements.txt

The absolute path selects the server environment's Python when installing the application's requirements. section 3.4.1

How Road to Kubernetes covers it

How deep it goes
Walks through creating and using environments, while noting they are not complete isolation; does not explain venv internals.
Examples
Shows platform-specific creation and activation commands, then installs application requirements using an absolute Python path on a server.
What it assumes
Assumes an installed Python interpreter and command-line access, but teaches virtual-environment setup from the first command.
What you can do after
Operate/configure it to create a project environment and install dependencies locally or on an Ubuntu server.
How it connects
Connects virtual environments to pip, requirements.txt, FastAPI, and Ubuntu's python3-venv package.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Road to Kubernetes. The section links point to the parts of the book it draws on.