← Python from Scratch Lesson 58 of 78 · 5 XP

Virtual environments: venv

Theory

Machine translation, not yet reviewed by a native speaker.

Imagine two projects: one needs Django 4, the other Django 5. If you install everything system-wide, the versions will get in each other's way. The solution is a virtual environment: a separate folder with its own Python and its own libraries for each project.

Create and activate it (Linux, macOS, WSL):

cd my_project
python3 -m venv .venv          # create an environment in the .venv folder
source .venv/bin/activate      # activate it

On Windows (PowerShell): .venv\Scripts\Activate.ps1.

Once it's active, (.venv) appears at the start of the terminal line. Now pip install installs packages into this project only.

pip install -r requirements.txt
python manage.py runserver
deactivate                     # deactivate

Good habits:

  • one environment per project, with the .venv folder in the project root;
  • .venv is not put into git (add it to .gitignore); you commit requirements.txt instead, which lets you recreate the environment;
  • you have to activate the environment again every time you open a new terminal — otherwise you'll get the familiar ModuleNotFoundError: No module named 'django'.

On Kali, Debian and Ubuntu the system pip is deliberately blocked (the externally-managed-environment error) so that system programs don't break. venv is the right way around that.

Sign up for free to mark finished lessons and track your progress.