Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Python Virtual Environments and pip: A Beginner-Friendly Guide

Learn why Python projects need virtual environments, how to create and activate a venv on Windows, macOS and Linux, use pip, pin dependencies in requirements.txt, and when to use pipx, Poetry or uv.

Sumit KumarUpdated Oct 11, 20263 min readPython
Python Virtual Environments and pip: A Beginner-Friendly Guide

Sooner or later every Python developer hits this: project A needs Django 4.2, project B needs Django 5.1, and installing one breaks the other. The fix is a virtual environment, an isolated folder with its own Python and its own packages for each project. Combined with pip, it's the foundation of every professional Python setup.

Why you need virtual environments#

Python virtual environment workflow: create venv, activate, pip install, freeze requirements and deactivate, with isolated project environments
  • No version conflicts: each project gets exactly the package versions it needs.
  • Reproducible setups: teammates and servers can recreate your environment exactly.
  • Clean system Python: you never break tools your operating system depends on.
  • Easy cleanup: delete the folder and the environment is gone.
Don't use sudo pip

Installing packages globally with sudo pip install can break system tools. Newer Linux distributions block it with an "externally-managed-environment" error for exactly this reason. Use a virtual environment instead.

Creating a virtual environment#

Python 3 ships with the venv module, so there's nothing to install.

Bash
mkdir weather-app && cd weather-app
python -m venv .venv          # creates a .venv folder

.venv is the most common name: it's hidden on macOS/Linux and editors like VS Code detect it automatically.

Activating and deactivating#

PlatformActivate command
macOS / Linux (bash, zsh)source .venv/bin/activate
Windows PowerShell.venv\Scripts\Activate.ps1
Windows Command Prompt.venv\Scripts\activate.bat
Bash
(.venv) $ which python        # .../weather-app/.venv/bin/python
(.venv) $ python --version
(.venv) $ deactivate          # back to the system Python

The (.venv) prefix in your prompt shows the environment is active. Activation simply puts the environment's bin (or Scripts) folder first on your PATH.

PowerShell error?

If Windows says scripts are disabled, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, then activate again.

Installing packages with pip#

Bash
pip install requests                 # latest version
pip install "django>=5.0,<5.2"       # version range
pip install fastapi==0.115.0         # exact version
pip install -U requests              # upgrade
pip uninstall requests
pip list                             # what's installed
pip show requests                    # details and dependencies

Use python -m pip instead of plain pip if you're ever unsure which Python a pip command belongs to. It guarantees pip installs into the interpreter you're running.

Sharing dependencies with requirements.txt#

Bash
pip freeze > requirements.txt        # save exact versions
Text
# requirements.txt
certifi==2024.8.30
charset-normalizer==3.4.0
idna==3.10
requests==2.32.3
urllib3==2.2.3
Bash
# On another machine
git clone https://github.com/you/weather-app.git
cd weather-app
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt      # identical environment

Separating dev dependencies#

Text
# requirements-dev.txt
-r requirements.txt
pytest==8.3.3
ruff==0.7.1

What to commit to Git#

CommitDon't commit
requirements.txt or pyproject.toml + lock fileThe .venv/ folder
Your source code__pycache__/, *.pyc
.python-version (optional).env files with secrets
Text
# .gitignore
.venv/
__pycache__/
*.pyc
.env

A complete example#

Bash
python -m venv .venv
source .venv/bin/activate
pip install requests
pip freeze > requirements.txt
Python
# weather.py
import requests

def get_temperature(city: str) -> float:
    res = requests.get(
        "https://api.open-meteo.com/v1/forecast",
        params={"latitude": 19.07, "longitude": 72.88, "current": "temperature_2m"},
        timeout=10,
    )
    res.raise_for_status()
    return res.json()["current"]["temperature_2m"]

if __name__ == "__main__":
    print(f"Mumbai: {get_temperature('Mumbai')}°C")

Modern tooling#

venv + pip is all you need to start. As projects grow, these tools add convenience:

ToolWhat it addsGood for
uvExtremely fast drop-in for pip and venv, lock files, Python version managementMost new projects
Poetrypyproject.toml, lock file, dependency groups, publishingLibraries and apps that need strict locking
pipxInstalls CLI tools (like ruff, black) in their own isolated envsGlobal command-line tools
condaManages non-Python libraries too (CUDA, C libraries)Data science and ML
pyenvInstalls and switches between Python versionsTesting several Python versions
Bash
# The same workflow with uv
uv venv
uv pip install requests
uv pip freeze > requirements.txt

# or the project workflow
uv init weather-app && cd weather-app
uv add requests          # updates pyproject.toml and uv.lock
uv run weather.py        # runs inside the project environment

Troubleshooting#

  • "ModuleNotFoundError" after installing: the environment isn't active, or your editor is using a different interpreter. In VS Code, run "Python: Select Interpreter" and pick .venv.
  • Moved or renamed the project folder: virtual environments contain absolute paths. Delete .venv and recreate it.
  • Wrong Python version: create the venv with a specific interpreter, e.g. python3.12 -m venv .venv.
  • Dependency conflict errors: run pip check to see which packages disagree.

New to Python? Start with Python basics for beginners and Python collections.

Key takeaways#

  • Create one virtual environment per project with python -m venv .venv.
  • Activate it before installing packages, and never install project packages globally.
  • Use pip freeze > requirements.txt and pip install -r requirements.txt to reproduce environments.
  • Commit dependency files, not the .venv folder.
  • Graduate to uv or Poetry for lock files and faster installs, and pipx for global CLI tools.