Python Virtual Environments: A Practical Guide with venv and pip
Learn how Python virtual environments isolate project dependencies, how to create and activate a .venv, install packages with pip, manage dependencies, and avoid common environment problems.

Tools used: Python, pip, VS Code, Terminal, Git
Prerequisites: Basic Python knowledge and familiarity with running commands in a terminal.
Python Virtual Environments: A Practical Guide with venv and pip
Installing Python packages globally can become a problem surprisingly quickly.
One project may need one version of a library while another project needs a different version. Without isolation, changing one project can accidentally affect another.
Python virtual environments solve this problem by giving each project its own isolated Python environment.
In this guide, you'll learn how to create and use virtual environments with Python's built-in venv module, install packages with pip, manage dependencies, configure VS Code, and troubleshoot common problems.
Quick answer: Create a virtual environment with
python -m venv .venv, activate it, install packages withpip, and keep.venvout of Git.
Python Virtual Environments at a Glance
| Task | Command |
|---|---|
| Create environment | python -m venv .venv |
| Activate on Windows | .venv\Scripts\activate |
| Activate on macOS/Linux | source .venv/bin/activate |
| Install package | python -m pip install requests |
| List packages | python -m pip list |
| Save dependencies | python -m pip freeze > requirements.txt |
| Install dependencies | python -m pip install -r requirements.txt |
| Leave environment | deactivate |
| Check Python | python --version |
| Check pip | python -m pip --version |
The Python Packaging User Guide recommends using virtual environments when working with third-party packages.
Why Do Python Projects Need Virtual Environments?
Imagine you have two projects.
Project A
Project A
└── Django 4.xProject B
Project B
└── Django 5.xIf both projects depend on packages installed into the same global Python environment, changing dependencies for one project can create problems for the other.
A virtual environment gives each project its own package installation location.
The environments use a base Python installation while keeping their project packages isolated.
What Is a Virtual Environment?
A virtual environment is an isolated Python environment created for a specific project.
It contains its own:
- Python executable
- installed packages
- package installation location
- environment configuration
For example:
my-project/
├── .venv/
├── app.py
├── requirements.txt
└── README.mdThe .venv directory belongs to the development environment, not your application source code.
Python's documentation recommends treating virtual environments as disposable and recreating them when necessary rather than moving or copying them between systems.
Creating Your First Virtual Environment
First, create a project directory.
mkdir python-demo
cd python-demoNow create the environment.
Windows
py -m venv .venvmacOS/Linux
python3 -m venv .venvYou can also use:
python -m venv .venvThe command creates a .venv directory containing the environment.
Activating the Environment
Creating the environment is not enough.
You normally activate it before installing and using project dependencies.
Windows PowerShell
.venv\Scripts\Activate.ps1Windows Command Prompt
.venv\Scripts\activatemacOS/Linux
source .venv/bin/activateAfter activation, your terminal usually shows the environment name:
(.venv) C:\projects\python-demo>Now package installations go into that environment.
The official packaging guide documents these activation commands for Windows and Unix-like systems.
Verify the Environment
After activation, check Python:
python --versionThen check where Python is coming from.
Windows
where pythonmacOS/Linux
which pythonYou should see a path associated with your .venv.
For example:
python-demo\.venv\Scripts\python.exeThis confirms that your project is using the virtual environment's interpreter.
Installing Packages with pip
Once the environment is active, you can install packages.
For example:
python -m pip install requestsYou can verify the installation:
python -m pip show requestsOr list installed packages:
python -m pip listExample:
Package Version
---------- -------
pip ...
requests ...Using:
python -m pipis useful because it makes it explicit that pip is being executed through the Python interpreter you're currently using.
Installing Multiple Packages
Suppose you're building a small API.
You might install:
python -m pip install fastapi uvicornNow your environment contains:
.venv
├── fastapi
├── uvicorn
└── dependencies...Your global Python installation does not need those project-specific packages.
Understanding requirements.txt
A common way to describe Python dependencies is a requirements.txt file.
For example:
fastapi
uvicorn
requestsYou can install them with:
python -m pip install -r requirements.txtYou can also generate a requirements file from an existing environment:
python -m pip freeze > requirements.txtThen another developer can recreate the environment:
python -m pip install -r requirements.txtThis creates a simple dependency workflow:
A Complete Python Project Setup
A typical beginner project might look like this:
weather-api/
├── .venv/
├── app.py
├── requirements.txt
├── .gitignore
└── README.mdCreate the environment:
python -m venv .venvActivate it.
Install dependencies:
python -m pip install requestsCreate your application:
import requests
response = requests.get("https://example.com")
print(response.status_code)Save the dependency list:
python -m pip freeze > requirements.txtNow the project contains both the source code and a description of its Python dependencies.
Never Commit .venv to Git
Your virtual environment should normally not be committed to Git.
Add this to .gitignore:
.venv/
venv/
__pycache__/
*.pycWhy?
Because .venv contains environment-specific files and installed packages.
Instead of committing the environment itself, commit the files needed to recreate it:
.gitignore
requirements.txt
app.py
README.mdPython's current documentation explicitly notes that virtual environments should not be checked into source control.
Recreating an Environment on Another Computer
Imagine your project is stored on GitHub.
Another developer clones it:
git clone https://github.com/example/python-project.git
cd python-projectThey create a new environment:
python -m venv .venvActivate it.
Then install the dependencies:
python -m pip install -r requirements.txtThe environment is recreated without committing .venv.
This is much more portable than sharing the virtual environment directory itself.
How pip and venv Work Together
They solve different problems.
| Tool | Purpose |
|---|---|
| Python | Runs Python programs |
| venv | Creates isolated environments |
| pip | Installs Python packages |
| requirements.txt | Records dependencies |
| Git | Tracks project source code |
A useful mental model is:
Python
↓
venv
↓
Project Environment
↓
pip
↓
Packages
↓
ApplicationUpdating pip
You can check your pip version:
python -m pip --versionYou can upgrade pip with:
Windows
py -m pip install --upgrade pipmacOS/Linux
python3 -m pip install --upgrade pipThe Python Packaging User Guide documents these commands for supported Python environments.
Installing a Specific Package Version
Sometimes a project requires a particular version.
For example:
python -m pip install requests==2.32.5You can also specify a minimum version:
python -m pip install "requests>=2.30"Or a version range:
python -m pip install "requests>=2.30,<3"This becomes important when applications depend on specific library behavior.
Checking Installed Packages
Use:
python -m pip listFor detailed information:
python -m pip show requestsTo check outdated packages:
python -m pip list --outdatedBe careful about upgrading dependencies blindly in production projects.
A package update can introduce breaking changes.
Deactivating a Virtual Environment
When you're finished:
deactivateYour terminal returns to the normal Python environment.
You can activate the same environment again later.
source .venv/bin/activateor on Windows:
.venv\Scripts\activateYou do not need to recreate the environment every time you open the project.
Deleting and Recreating a Virtual Environment
Virtual environments are designed to be disposable.
If an environment becomes corrupted, you can remove it and recreate it.
Windows
Remove-Item -Recurse -Force .venvmacOS/Linux
rm -rf .venvThen:
python -m venv .venvActivate it:
source .venv/bin/activateInstall dependencies:
python -m pip install -r requirements.txtThis is often much cleaner than trying to repair a broken environment manually.
VS Code and Python Virtual Environments
VS Code can detect Python environments inside your project.
A common structure is:
project/
├── .venv/
├── src/
├── requirements.txt
└── README.mdAfter opening the project in VS Code, select the Python interpreter associated with .venv.
The important part is that your editor, terminal, testing tools, and application should use the same environment.
Common Problem: pip Installs Into the Wrong Python
You run:
pip install requestsbut your application says:
ModuleNotFoundError: No module named 'requests'One possible cause is that pip and python point to different installations.
Check:
python --version
python -m pip --versionOn Windows:
where python
where pipOn macOS/Linux:
which python
which pipUsing:
python -m pip install requestshelps ensure the package is installed for the Python interpreter you're actually using.
Common Problem: Environment Is Not Activated
You create:
python -m venv .venvand immediately run:
pip install requestsYou may accidentally install the package outside your project environment.
Activate the environment first:
source .venv/bin/activateThen:
python -m pip install requestsCommon Problem: PowerShell Blocks Activation
On some Windows configurations, PowerShell can block script execution.
If activation fails, you may see an execution-policy-related message.
You can use Command Prompt instead:
.venv\Scripts\activateOr review your PowerShell execution-policy configuration according to your organization's security requirements.
Do not blindly disable security controls just to activate a Python environment.
Common Problem: Python Command Is Not Found
If this fails:
python --versiontry:
python3 --versionOn Windows, the Python launcher may also work:
py --versionThen create the environment with:
py -m venv .venvCommon Problem: Linux Says the Environment Cannot Be Created
Some Linux distributions manage system Python installations externally.
Modern Python packaging specifications can mark an interpreter as externally managed and guide users toward virtual environments rather than modifying the system installation.
For a project environment, try:
python3 -m venv .venvIf your distribution reports that the required venv support is missing, install the appropriate distribution package according to your Linux distribution's documentation.
Virtual Environment vs Global Installation
| Approach | Global Install | Virtual Environment |
|---|---|---|
| Project isolation | ❌ | ✅ |
| Different dependency versions | Difficult | Easy |
| Safer project setup | ❌ | ✅ |
| Reproducible development | Limited | Better |
| Easy cleanup | ❌ | ✅ |
| Recommended for third-party project packages | Usually not | ✅ |
The main advantage is isolation.
Virtual Environment vs virtualenv
You may see both venv and virtualenv.
venv
venv is included in modern Python and is part of Python's standard library.
python -m venv .venvvirtualenv
virtualenv is a separate third-party tool.
python -m pip install virtualenvThen:
python -m virtualenv .venvFor many normal application projects, the built-in venv module is enough.
Virtual Environments in AI and Data Science
Virtual environments become particularly useful in AI and data projects.
One project might use:
Project A
Python libraries
├── numpy
├── pandas
└── scikit-learnAnother might use:
Project B
Python libraries
├── numpy
├── pandas
└── torchDifferent projects can evolve independently.
This is especially useful when experimenting with machine learning libraries, APIs, notebooks, and different dependency versions.
Virtual Environments in Backend Development
Python backend projects frequently have multiple dependencies.
For example:
FastAPI
Uvicorn
SQLAlchemy
PostgreSQL driver
PydanticA project environment keeps those dependencies associated with the application instead of installing everything globally.
A typical workflow becomes:
mkdir backend-api
cd backend-api
python -m venv .venvActivate:
source .venv/bin/activateInstall:
python -m pip install fastapi uvicornSave dependencies:
python -m pip freeze > requirements.txtA Better Daily Python Workflow
A practical workflow looks like this:
For a new project:
mkdir my-project
cd my-project
python -m venv .venvActivate it.
Then:
python -m pip install requestsWork on your application.
Finally:
python -m pip freeze > requirements.txtCommit:
app.py
requirements.txt
.gitignore
README.mdDo not commit:
.venv/Best Practices
1. Use one environment per project
project-a/.venv
project-b/.venv
project-c/.venvThis keeps dependencies isolated.
2. Use .venv as the directory name
It is easy to recognize and works well with modern development tools.
3. Do not commit .venv
Keep it in .gitignore.
4. Record dependencies
For projects using requirements.txt:
python -m pip freeze > requirements.txt5. Verify your interpreter
When debugging dependency problems, check:
python -m pip --version6. Recreate broken environments
Don't spend hours repairing a badly corrupted environment.
Delete and recreate it when appropriate.
7. Keep development and production concerns separate
A local virtual environment is useful for development, but production deployment may use containers, system packaging, or other deployment mechanisms depending on the application.
The Python Packaging User Guide specifically distinguishes development virtual environments from broader production packaging and deployment approaches.
Mini Project: Build a Python Dependency Demo
Let's create a small project to practice everything.
Step 1: Create the project
mkdir dependency-demo
cd dependency-demoStep 2: Create the environment
python -m venv .venvStep 3: Activate it
Windows:
.venv\Scripts\activatemacOS/Linux:
source .venv/bin/activateStep 4: Install Requests
python -m pip install requestsStep 5: Create app.py
import requests
url = "https://example.com"
response = requests.get(url, timeout=10)
print("Status:", response.status_code)Step 6: Run it
python app.pyStep 7: Save dependencies
python -m pip freeze > requirements.txtStep 8: Add Git ignore
Create .gitignore:
.venv/
__pycache__/
*.pycYou now have a basic Python project with an isolated development environment.
Understanding the Mental Model
The easiest way to remember everything is:
Python
│
├── Base installation
│
└── Project
│
└── .venv
│
├── Python
├── pip
└── Project packagesYour source code lives outside .venv.
Your environment contains the dependencies required to run that source code.
Your Git repository stores the project and dependency instructions, not the environment itself.
Python Environment Cheat Sheet
Create
python -m venv .venvActivate — Windows
.venv\Scripts\activateActivate — macOS/Linux
source .venv/bin/activateInstall
python -m pip install package-nameUninstall
python -m pip uninstall package-nameList packages
python -m pip listSave dependencies
python -m pip freeze > requirements.txtInstall dependencies
python -m pip install -r requirements.txtCheck Python
python --versionCheck pip
python -m pip --versionDeactivate
deactivateCommon Mistakes to Avoid
Installing everything globally
pip install package1 package2 package3This can make unrelated projects depend on the same environment.
Prefer a project-specific virtual environment.
Committing .venv
Don't push the entire environment to Git.
Use:
.venv/Using the wrong interpreter
If your package is installed but Python cannot import it, check which Python and pip you're using.
Copying .venv between computers
Virtual environments are not designed to be portable copies.
Create a new environment and reinstall the dependencies.
Forgetting dependency management
A project that works only on one developer's computer is difficult to maintain.
Keep dependency information in the repository.
Why This Matters for Developers
Virtual environments are a small Python concept, but they become extremely important as your projects grow.
They help with:
- Backend development
- Data science
- Machine learning
- Automation
- APIs
- Web applications
- Testing
- CLI applications
- AI applications
- Open-source projects
If you're learning Python professionally, understanding environments, packages, and dependencies should be part of your core workflow.
Interview Questions
1. What is a Python virtual environment?
An isolated Python environment that allows a project to use its own interpreter context and installed packages without mixing them with other project environments.
2. What command creates a virtual environment?
python -m venv .venv3. Why shouldn't .venv be committed to Git?
It contains environment-specific files and installed packages and should be recreated from project dependency information instead.
4. What is pip?
pip is the standard Python package installer used to install and manage Python packages.
5. What is requirements.txt?
A file commonly used to record Python project dependencies so they can be installed into another environment.
6. How do you install requirements?
python -m pip install -r requirements.txt7. How do you deactivate a virtual environment?
deactivate8. Why use python -m pip instead of simply pip?
It helps ensure that pip is executed through the Python interpreter you're currently using, reducing confusion when multiple Python installations exist.
FAQ
Do I need a virtual environment for every Python project?
For projects using third-party dependencies, using a separate virtual environment is a strong default because it keeps dependencies isolated.
Is .venv part of my application?
No. It is the project's local Python environment.
Should .venv be uploaded to GitHub?
No. Add it to .gitignore.
Can I delete .venv?
Yes. Virtual environments are designed to be disposable.
Do I need to recreate .venv every time I open VS Code?
No. Once created, you normally reactivate or select the existing environment.
Is venv a Python package?
No. venv is part of Python's standard library.
Can multiple projects use the same virtual environment?
They technically can, but separate environments are generally better because each project can have independent dependencies.
Final Takeaway
Python virtual environments are one of the simplest ways to keep projects clean and predictable.
The essential workflow is:
Create project
↓
Create .venv
↓
Activate .venv
↓
Install packages with pip
↓
Develop and test
↓
Record dependencies
↓
Commit source codeThe commands worth remembering are:
python -m venv .venv
python -m pip install package-name
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt
deactivateOnce you understand this workflow, starting a new Python backend, automation, AI, or data project becomes much more predictable.
Learn the environment before the dependencies—and your Python projects become much easier to manage.







Comments (0)
Be the first to share your thoughts.