Lesson 88 +10 XP

Virtual Environments

A virtual environment gives each project its own isolated set of packages. Projects can use different versions without fighting.

Why isolate?

Two projects may need different versions of the same library. Without isolation, installing one breaks the other. A venv fixes that.

Create a virtual environment


bash
python -m venv myenv

This makes a folder named myenv with its own Python and pip.

Activate it

On Windows:


bash
myenv\Scripts\activate

On macOS/Linux:


bash
source myenv/bin/activate

Install into the environment

Once active, use pip as usual. The packages go into the environment, not your system:


bash
pip install requests

Deactivate


bash
deactivate

Freeze your dependencies

Share what your project needs:


bash
pip freeze > requirements.txt

Others install it all at once:


bash
pip install -r requirements.txt

TL;DR

  • python -m venv name creates an isolated environment.
  • Activate it before installing packages.
  • deactivate leaves it.
  • requirements.txt shares dependencies.