Modules & Files
pip & Virtual Environments
Complete lesson for pip & Virtual Environments using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — pip & Virtual Environments
Section: Modules & Files. pip and virtual environments — isolate dependencies with venv, install packages with pip, freeze requirements, and avoid polluting the system Python.
Why virtual environments?
- Different projects need different package versions. Isolating them prevents conflicts.
- A venv has its own
site-packagesand its ownpython/pipexecutables. - Real-life analogy: each project gets its own toolbox instead of one shared messy drawer.
| Problem | Without venv | With venv |
|---|---|---|
| Version clash | Project A needs requests 2.x, B needs 1.x | Each env has its own copy |
| System Python | Easy to break OS tools | Leaves system site-packages alone |
| Reproducibility | Hard to know what was installed | requirements.txt pins versions |
| Collaboration | "Works on my machine" | Same install steps for everyone |
Create a venv with the standard library
python -m venv .venvcreates an environment in.venv/(common convention).- The stdlib
venvmodule is enough for most beginners; the third-partyvirtualenvtool is an alternative with extra features. - Always create venvs per project, not one global shared venv for everything.
# Commands (run in a terminal, not inside another unclear env):
# python -m venv .venv
# Windows PowerShell: .\.venv\Scripts\Activate.ps1
# Windows cmd: .\.venv\Scripts\activate.bat
# macOS / Linux: source .venv/bin/activate
# deactivate Activation differences by OS
- Activation only adjusts
PATHfor your shell session. - You can skip activation and call
.venv/Scripts/python.exe -m pip install ...directly.
| Shell | Activate | python location |
|---|---|---|
| PowerShell | .\.venv\Scripts\Activate.ps1 | .venv\Scripts\python.exe |
| cmd.exe | .\.venv\Scripts\activate.bat | .venv\Scripts\python.exe |
| bash/zsh | source .venv/bin/activate | .venv/bin/python |
| No activate | Call the interpreter by path | Same as above |
pip essentials
- Prefer
python -m pipso you install into the same interpreter you run. pip install package,pip install package==1.2.3,pip install -r requirements.txt.pip list,pip show package,pip uninstall package.
| Command | Purpose |
|---|---|
python -m pip install requests | Install latest compatible version |
python -m pip install requests==2.32.3 | Pin exact version |
python -m pip install -r requirements.txt | Install from file |
python -m pip freeze > requirements.txt | Export pinned set |
python -m pip list | Show installed distributions |
python -m pip show pip | Metadata for one package |
python -m pip install -U pip | Upgrade pip itself |
requirements.txt basics
- A text file listing distributions and optional version specifiers.
pip freezeoutputs exact pins (pkg==1.2.3) — great for apps; libraries often use broader ranges.- Commit
requirements.txt(or lock files) so teammates and servers install the same stack.
# Example requirements.txt
# requests==2.32.3
# rich>=13.0
# # comments start with # Typical project workflow
- 1) Create venv 2) Activate 3) Upgrade pip 4) Install deps 5) Freeze when stable.
- Add
.venv/to.gitignore— never commit the environment folder. - Document Python version (e.g. 3.12+) in README.
| Step | Command |
|---|---|
| Create | python -m venv .venv |
| Activate (PS) | .\.venv\Scripts\Activate.ps1 |
| Upgrade pip | python -m pip install -U pip |
| Install | python -m pip install -r requirements.txt |
| Freeze | python -m pip freeze > requirements.txt |
| Leave env | deactivate |
venv vs virtualenv vs conda
- This lesson focuses on
venv+pip— the baseline every Python developer should know.
| Tool | Comes with | Notes |
|---|---|---|
venv | Stdlib | Default choice for pure Python apps |
virtualenv | PyPI package | Faster/older support; similar UX |
conda/mamba | Anaconda ecosystem | Also manages non-Python binaries |
poetry/uv/pipenv | Third-party | Higher-level dependency workflows |
Where packages land
- Inside a venv, installs go to
.venv/Lib/site-packages(Windows) or.venv/lib/pythonX.Y/site-packages. import site; site.getsitepackages()shows candidate directories.- If
pipandpythondisagree, you installed into the wrong environment.
import sys
import site
print("executable:", sys.executable)
print("prefix:", sys.prefix)
print("site-packages:")
for p in site.getsitepackages():
print(" ", p) Advanced — pip & Virtual Environments
Programmatic venv creation
- The
venvmodule can create environments from Python code (venv.EnvBuilder). - Useful for tooling and teaching demos; day-to-day use is still the CLI.
import venv
from pathlib import Path
env_dir = Path("mini_env")
builder = venv.EnvBuilder(with_pip=True)
builder.create(env_dir)
print("created:", env_dir.resolve())
print("pyvenv.cfg exists:", (env_dir / "pyvenv.cfg").exists()) Pinning strategies
- Apps: pin exact versions with
pip freezefor reproducible deploys. - Libraries: specify minimums / compatible ranges; let apps pin.
- Separate
requirements.txt(runtime) andrequirements-dev.txt(pytest, linters).
Common pip failures
- Permission errors → you are installing into system Python; use a venv.
- Wrong package installed → ran
pipfrom a different interpreter thanpython. - Build errors → package needs compilers or a wheel for your platform/Python version.
| Symptom | Likely cause | Fix |
|---|---|---|
command not found: pip | Scripts not on PATH | python -m pip ... |
| Installs but import fails | Multiple Pythons | Compare sys.executable |
| SSL / network errors | Proxy or offline network | Fix network or use wheels cache |
| Conflict resolutions | Incompatible pins | Relax pins or align versions |
Editable installs
pip install -e .installs your project in editable mode so code changes apply without reinstall.- Needs packaging metadata (
pyproject.tomlor setuptools config). - Best way for local package development — better than
sys.pathhacks.
Security and trust basics
- Prefer well-known packages; check PyPI project pages and download stats.
- Pin versions in production; review upgrades.
- Use private indexes carefully; configure
pipindex URL only when required.
Reading environment markers
- Requirements can include environment markers:
package; python_version>="3.10". - Useful for OS-specific or version-specific dependencies.
# Example line for requirements files:
# pywin32>=306; sys_platform == "win32" Tricky Interview Points
Q1) What is a virtual environment?
Answer An isolated directory with its own Python interpreter and site-packages so project dependencies do not clash.
Q2) How do you create and activate a venv?
Answer python -m venv .venv, then run the OS-specific Activate script under .venv/Scripts (Windows) or source .venv/bin/activate (Unix).
Q3) Why prefer python -m pip over bare pip?
Answer It guarantees the pip module runs with that same Python interpreter, avoiding installs into the wrong environment.
Q4) What is requirements.txt?
Answer A file listing dependencies (often pinned) that pip install -r can reproduce.
Q5) What does pip freeze do?
Answer Lists installed distributions as package==version pins, commonly redirected into requirements.txt.
Q6) Should you commit .venv to git?
Answer No. Commit requirements or lock files; recreate the venv on each machine.
Q7) venv vs virtualenv?
Answer venv is in the standard library. virtualenv is a third-party tool with similar goals and some extra features/older Python support.
Q8) How do you upgrade pip inside a venv?
Answer python -m pip install -U pip
Q9) What is an editable install?
Answer pip install -e . links your project into site-packages so local edits are imported immediately.
Q10) Import works in the IDE but not in the terminal — why?
Answer Different interpreters/environments. Compare sys.executable and which pip is on PATH.
Q11) How do you uninstall a package?
Answer python -m pip uninstall package_name
Q12) What is site-packages?
Answer The directory where third-party distributions are installed and searched during import.
Simple Programs
Show interpreter and site-packages
import sys
import site
print("executable:", sys.executable)
print("version:", sys.version.split()[0])
print("prefix:", sys.prefix)
print("base_prefix:", getattr(sys, "base_prefix", sys.prefix))
print("in_venv:", sys.prefix != getattr(sys, "base_prefix", sys.prefix))
for p in site.getsitepackages():
print("site:", p) Create a venv folder with venv.EnvBuilder
import venv
from pathlib import Path
env_dir = Path("pyv_demo_env")
if not env_dir.exists():
venv.EnvBuilder(with_pip=True).create(env_dir)
cfg = (env_dir / "pyvenv.cfg").read_text(encoding="utf-8")
print(cfg.splitlines()[0])
print("Scripts/bin exists:", (env_dir / "Scripts").exists() or (env_dir / "bin").exists()) Write and parse a requirements.txt
from pathlib import Path
req = Path("sample_requirements.txt")
req.write_text(
"# demo requirements\n"
"requests==2.32.3\n"
"rich>=13.0\n"
"pytest; extra == 'dev'\n",
encoding="utf-8",
)
def parse_requirements(text: str) -> list[str]:
out: list[str] = []
for line in text.splitlines():
s = line.strip()
if not s or s.startswith("#"):
continue
out.append(s)
return out
rows = parse_requirements(req.read_text(encoding="utf-8"))
print("parsed", len(rows), "entries")
for r in rows:
print("-", r) List installed distributions via importlib.metadata
from importlib.metadata import distributions
names = sorted({d.metadata["Name"] for d in distributions() if d.metadata.get("Name")})
print("installed count:", len(names))
print("first 10:", ", ".join(names[:10])) Simulate pip freeze style pins from metadata
from importlib.metadata import distributions
pins: list[str] = []
for d in distributions():
name = d.metadata.get("Name")
version = d.metadata.get("Version")
if name and version:
pins.append(f"{name}=={version}")
pins = sorted(pins, key=str.lower)
Path = __import__("pathlib").Path
out = Path("freeze_demo.txt")
out.write_text("\n".join(pins[:20]) + "\n", encoding="utf-8")
print(out.read_text(encoding="utf-8")) Check whether a module is importable (dependency sanity)
import importlib.util
candidates = ["math", "json", "requests", "rich", "not_a_real_pkg_xyz"]
for name in candidates:
spec = importlib.util.find_spec(name)
print(f"{name:20} {'YES' if spec else 'NO'}") Compare sys.prefix vs base_prefix (venv detection)
import sys
base = getattr(sys, "base_prefix", sys.prefix)
print("prefix :", sys.prefix)
print("base_prefix:", base)
if sys.prefix == base:
print("Status: system / base interpreter")
else:
print("Status: virtual environment active") Problem Solving Tricks
- Always
python -m pipto target the intended interpreter. - Put
.venv/in.gitignore. - Create one venv per project directory.
- Activation is optional if you call
.venv/Scripts/python.exeexplicitly. - Freeze after the app stabilizes; review the file before committing.
- Keep runtime and dev requirements separate.
- If imports fail, print
sys.executablefirst. - Upgrade pip inside the venv before installing complex stacks.
- Prefer wheels; read build errors as “wrong Python version / missing compiler”.
- Document the minimum Python version next to your requirements.
Practice Programs List
- Create a
.venv, activate it, and installrequests, thenimport requestssuccessfully. - Generate
requirements.txtwithpip freezeand recreate the env from scratch. - Split deps into
requirements.txtandrequirements-dev.txt. - Demonstrate installing with the wrong pip and show mismatched
sys.executable. - Write a short README section with Windows and Linux activate commands.
- Use
pip showto find a package’s Location and Requires lines. - Create a venv programmatically with
venv.EnvBuilderand printpyvenv.cfg. - Try
pip install -e .on a tiny package withpyproject.toml. - Parse a requirements file and validate that each line is either a comment or a requirement.
- Compare
venvwith a tool likeuvor Poetry at a high level (notes only). - Break and fix a version conflict between two pinned packages in a practice file.
- Detect whether code is running inside a venv using
sys.prefix != sys.base_prefix.