03 ecosystem

A global pip install is how you end up with three projects fighting over one version I stopped doing that years ago Every project gets its own environment

Table of Contents

Virtual environments

Create one in the project directory

python3 -m venv venv

python3 -m venv --help was checked The -m form uses the interpreter you just named , no ambiguity

Activate it on Linux or macOS:

source venv/bin/activate

Your prompt gains (venv) That is the sign you are inside the box

Leave it:

deactivate

Windows activation is .\venv\Scripts\Activate.ps1 Test this in your lab first

Do not commit the venv/ directory Add it to .gitignore

pip

pip pulls packages from PyPI Always run it through the same interpreter

python3 -m pip install requests
python3 -m pip list

The -m form ties pip to the same interpreter as the code it installs for Pin a version when a tool breaks after an upgrade Check the package index for the current release before writing a pinned version into a lockfile

Requirements

Freeze the environment so another machine can rebuild it

python3 -m pip freeze > requirements.txt
python3 -m pip install -r requirements.txt

requirements.txt is a snapshot It is not a lockfile and it does not solve every dependency conflict Read the diff before you commit it

Common errors

  • No module named venv -> your Python install is incomplete , install the venv package for your distro
  • externally-managed-environment -> your distro blocks global installs , use the venv above
  • ModuleNotFoundError after install -> wrong interpreter , check which python3 and python3 -m pip list

Environment first , packages second That order saves the most time

Posted