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

Code

bash
python -m venv myenv

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

Activate it

On Windows:

Code

bash
myenv\Scripts\activate

On macOS/Linux:

Code

bash
source myenv/bin/activate

Install into the environment

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

Code

bash
pip install requests

Deactivate

Code

bash
deactivate

Freeze your dependencies

Share what your project needs:

Code

bash
pip freeze > requirements.txt

Others install it all at once:

Code

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.