When you start a second Python project and run pip install requests — that library gets installed globally, for the entire system. At first it feels convenient. Then problems start.
The problem: version conflicts
Project A requires requests==2.28
Project B requires requests==2.31
Both projects on the same machine. You can’t install two versions globally — only one can win.
This is exactly why virtual environments (venv) exist.
What is a venv?
A virtual environment is an isolated directory containing:
- A separate Python interpreter
- A separate pip
- Separate packages
Each project gets its own environment. Packages from one project are invisible to another.
project-a/
├── .venv/ ← project A's environment (requests 2.28)
└── main.py
project-b/
├── .venv/ ← project B's environment (requests 2.31)
└── main.py
Creating and activating
Create
python -m venv .venv
The leading dot in .venv is a convention. The folder is only visible in a file manager if hidden files are shown.
Activate
# Mac / Linux:
source .venv/bin/activate
# Windows PowerShell:
.venv\Scripts\Activate.ps1
# Windows cmd:
.venv\Scripts\activate.bat
After activation, (.venv) appears at the start of the terminal prompt — that’s how you know the environment is active.
Verify
which python # Should show a path inside .venv (Mac/Linux)
where python # Windows
Deactivate
deactivate
Installing packages into a venv
Once activated, all pip install commands only affect this environment:
pip install requests python-dotenv
Check what’s installed:
pip list
requirements.txt — pinning versions
So that another developer (or your CI/CD pipeline) can reproduce the same environment:
# Save current packages with versions:
pip freeze > requirements.txt
# Install from the file:
pip install -r requirements.txt
Contents of requirements.txt:
requests==2.31.0
python-dotenv==1.0.0
certifi==2024.2.2
...
What to add to .gitignore
The .venv folder is not committed — it’s large and can always be recreated from requirements.txt:
.venv/
__pycache__/
*.pyc
Common issues
Installed a package but the program can’t find it
The venv is probably not activated. Check for (.venv) in the terminal prompt.
Windows error: “cannot be loaded because running scripts is disabled”
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
VS Code doesn’t see the .venv
Press Ctrl+Shift+P → Python: Select Interpreter → choose the interpreter from .venv.
Summary
One rule: one project — one virtual environment. This prevents version conflicts and makes the project reproducible on any machine.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!