Python Tutorial · Going Further · Lesson 38 of 42

Python pip and Virtual Environments

Install packages with pip inside an isolated virtual environment.

Why virtual environments?

Different projects need different package versions. A virtual environment is a private folder of packages for one project, so projects don't conflict.

Create and activate a virtual environment
python3 -m venv .venv
source .venv/bin/activate      # macOS / Linux
# .venv\Scripts\activate      # Windows
python --version

Output

Python 3.12.3

Run this on your computer — see “Get Started” for setup.

Installing packages

With the environment activated, pip install adds packages from PyPI (the Python Package Index):

Install a package
pip install requests
python -c "import requests; print(requests.__version__)"

Output

2.32.3

Run this on your computer — see “Get Started” for setup.

Recording dependencies

Save exact versions to requirements.txt so others (and your servers) can install the same set:

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

Modern projects often use pyproject.toml with tools like uv or Poetry, which also lock versions — the ideas are the same.

Test yourself

Which command creates a virtual environment in the folder .venv?

  1. pip install venv
  2. python3 -m venv .venv
  3. python3 venv create
  4. virtualenv --new
Show answer

Answer: python3 -m venv .venv