The issue opens pre-filled with this page title and URL.
You are working on two Python projects: one uses Django 3.2, the other Django 4.2. Without isolation, installing the new version would overwrite the old one and break your first project. Virtual environments solve this problem by creating an isolated space for each project, with its own package versions.
A virtual environment is a directory containing a link to the Python interpreter and a dedicated space for packages. On Linux and macOS, venv creates symbolic links to the interpreter by default, not a copy (the --copies option forces a copy). If Python is updated on the system, the environment may therefore stop working: you then recreate it. Once you activate it, every pip install command affects only that environment: your system stays intact, and so do your other projects.
This guide shows you how to create, use and manage virtual environments with venv (the tool built into Python), then explores alternatives such as pipenv and uv.
What you will learn
This guide covers the whole life cycle of Python virtual environments. Each section comes with commands you can run right away.
By the end of this guide, you will be able to:
Understand the problem of dependency conflicts and why isolation is needed
Create a virtual environment with venv in a single command
Activate and deactivate the environment depending on your operating system
Install packages in isolation with pip
Manage dependencies with requirements.txt for reproducible environments
Choose the right alternative among venv, virtualenv, pipenv and uv
Why use a virtual environment?
The dependency conflict problem
Without a virtual environment, all your Python projects share the same globally installed packages. Here is what can go wrong:
With a virtual environment, each project has its own space:
With virtual environments, each project has its own .venv directory: Django 3.2 and Python 3.9 for A, Django 4.2 and Python 3.11 for B, Flask 2.3, SQLAlchemy 2.0 and Python 3.10 for C, with no conflict.Project AProject BProject C.venv/.venv/.venv/Django==3.2requests==2.25Python 3.9Django==4.2requests==2.31Python 3.11Flask==2.3SQLAlchemy==2.0Python 3.10
The Django, Flask and Python versions in the diagram are examples of existing projects. To follow this guide, you need Python 3.11 or newer.
Concrete benefits:
No conflicts, each project has its own package versions
Reproducibility, export requirements.txt and recreate the identical environment elsewhere
Safety, testing a new version cannot break other projects
Cleanliness, delete a project = delete its environment, nothing is left behind
Create a virtual environment with venv
The venv module has been built into Python since version 3.3, and there is nothing to install with the Python from python.org or the one on most other systems.
Step 1: Check Python
Before you start, check that Python 3.11 or later is installed:
Terminal window
python3--version
Expected output:Python 3.11.6 (or a later version)
Step 2: Create the environment
In your project directory, run:
Terminal window
python3-mvenv.venv
This command creates a .venv directory containing:
Directory/File
Contents
bin/ (Linux/macOS) or Scripts/ (Windows)
Python executables and activation scripts
lib/
Packages installed in this environment
include/
Header files for C extensions
pyvenv.cfg
Environment configuration
Swipe to see more
Step 3: Check the creation
List the contents of the directory you just created:
Terminal window
ls-la.venv/
You should see the bin/, lib/, include/ directories and the pyvenv.cfg file. With Python 3.13, venv also adds a lib64 link that points to lib and a .gitignore file.
Activate the virtual environment
Creating the environment does not activate it automatically. Activation changes your terminal so that it uses the environment's Python instead of the global Python.
How do you know whether the environment is active?
After activation, your prompt changes to show the name of the environment:
Terminal window
# Before activation
user@machine:~/my-project$
# After activation
(.venv) user@machine:~/my-project$
Additional check: the which python command (Linux/macOS) or where python (Windows) must point to .venv/bin/python:
/home/user/my-project/.venv/bin/python
whichpython
Deactivate the environment
When you have finished working on the project:
Terminal window
deactivate
The prompt goes back to normal and the python and pip commands use the global installation again.
Install packages with pip
Once the environment is active, pip installs packages only in that environment.
Install a package
Terminal window
pipinstallrequests
This command:
Downloads the requests package from PyPI
Installs it in .venv/lib/python3.x/site-packages/
Automatically installs its dependencies (urllib3, certifi, etc.)
Install a specific version
To guarantee compatibility, specify an exact version:
Terminal window
pipinstallrequests==2.31.0
The number 2.31.0 illustrates the syntax. This version is old: vulnerabilities have been published since and fixed in the 2.32 branch. On a real project, choose the current version, after checking it.
Available version syntaxes:
Syntax
Meaning
requests==2.31.0
Exact version
requests>=2.28.0
Minimum version
requests>=2.28,<3.0
Version range
requests~=2.31.0
Compatible with 2.31.x
Swipe to see more
List installed packages
Terminal window
piplist
Output of this form, versions vary:
Package Version
------------------ ---------
certifi 2023.11.17
charset-normalizer 3.3.2
idna 3.6
pip 23.3.1
requests 2.31.0
urllib3 2.1.0
Update a package
Updating a package installs the latest version available on PyPI that is compatible with your Python version, without asking for confirmation. It also touches transitive dependencies if the new version requires others. On a project whose requirements.txt is versioned, regenerate that file right afterwards, otherwise your local environment and your colleagues' silently diverge.
Terminal window
pipinstall--upgraderequests
Uninstall a package
Terminal window
pipuninstallrequests
Confirm with y when asked.
Manage dependencies with requirements.txt
The requirements.txt file lists all the dependencies of your project. It lets you recreate an identical environment on another machine.
Export the current dependencies
Terminal window
pipfreeze>requirements.txt
Generated content:
certifi==2023.11.17
charset-normalizer==3.3.2
idna==3.6
requests==2.31.0
urllib3==2.1.0
Install from requirements.txt
On a new machine or after cloning a project:
Create a virtual environment
Terminal window
python3-mvenv.venv
Activate the environment
Terminal window
source.venv/bin/activate
Install the dependencies
Terminal window
pipinstall-rrequirements.txt
All the dependencies are installed with the exact versions specified.
Best practices for requirements.txt
1. Separate direct from indirect dependencies
Create two files:
requirements.in, packages you use directly
requirements.txt, generated from the previous one by pip-compile (a pip-tools tool), includes the transitive dependencies with their exact versions
2. Version requirements.txt in Git
Terminal window
gitaddrequirements.txt
gitcommit-m"Add project dependencies"
3. Keep versions up to date
Periodically, check for security updates:
Terminal window
piplist--outdated
Remove a virtual environment
A virtual environment is a simple directory. To remove it:
Here is how to organize a Python project with a virtual environment:
my-project/
├── .venv/ # Virtual environment (excluded from Git)
├── .gitignore # Includes .venv/
├── requirements.txt # Dependencies
├── src/ # Source code
│ ├── __init__.py
│ └── main.py
├── tests/ # Tests
│ └── test_main.py
└── README.md
Minimal contents of .gitignore:
# Virtual environment
.venv/
venv/
env/
# Python cache
__pycache__/
*.pyc
*.pyo
# pip
pip-log.txt
Alternatives to venv
venv suits most projects, but other tools offer extra features.
Tool comparison
Read this table by the Use case column rather than by the strengths: these tools do not replace one another, they answer different constraints. The conda row stands apart, as it is the only one in the list that also installs non-Python system libraries (BLAS, CUDA, GDAL), which pip cannot do. The other four are limited to Python packages and differ mainly in installation speed and in the format used to lock versions.
Tool
Strengths
Use case
venv
Built into Python, simple
Standard projects
virtualenv
Faster creation, advanced options
CI/CD, multi-interpreter projects
pipenv
Pipfile.lock, integrated management
Teams, reproducibility
uv
Ultra-fast (Rust), pip-compatible
Modern projects, CI/CD
conda
Non-Python packages, data science
ML, scientific computing
Swipe to see more
virtualenv
Older than venv, of which it is the direct ancestor, virtualenv creates environments faster because it bundles a copy of pip instead of rebuilding it each time. Beware of a persistent misconception: virtualenv no longer creates Python 2 environments since version 20.22.0 of April 2023, and since 21.5.0 of June 2026 it requires a Python 3.9 or later interpreter, both to run and as the target. If you still need to serve Python 2, you need an old, frozen version of virtualenv.
Terminal window
pipinstallvirtualenv
virtualenv.venv
source.venv/bin/activate
pipenv
Combines a virtual environment and dependency management in a single tool. Uses Pipfile instead of requirements.txt.
Terminal window
pipinstallpipenv
pipenvinstallrequests# Creates the env and installs the package
pipenvshell# Activates the environment
Generated files:
Pipfile, readable dependencies
Pipfile.lock, exact locked versions
uv (recommended for new projects)
A modern tool written in Rust, announced by its publisher Astral as 10 to 100 times faster than pip for installing packages (the publisher's figure, published on the project repository: measure it on your own installations). The installation below, written for Linux x86_64, fetches the binary archive published on GitHub and the associated checksum file, then refuses to continue if the two do not match. The sha256sum --check command must answer OK; any other answer means the archive was altered or truncated, so do not extract anything in that case.
Terminal window
# Install uv from a verified archive (version 0.13.8, published on 2026-11-12)
Compatible with requirements.txt and pyproject.toml
Deterministic dependency resolution
Global cache shared between projects
pipx: install global CLI tools
Some Python tools are global CLIs (black, flake8, httpie...) that you want to use everywhere, not in one specific project.
Problem: installing them globally with pip can create conflicts.
Solution: pipx installs each tool in its own isolated environment, while making the command available globally.
One installation detail catches readers out on Debian 12+, Ubuntu 23.04+ and recent Fedora: these distributions mark their system Python as externally managed (file /usr/lib/python3.X/EXTERNALLY-MANAGED, defined by PEP 668), and pip install outside a virtual environment fails there with error: externally-managed-environment (observed on Debian 13 with Python 3.13.5 and pip 25.1.1). So go through the distribution package.
Terminal window
# Install pipx (recent Debian / Ubuntu: the system package is the official way)
sudoaptinstallpipx
# Elsewhere, or if the package does not exist:
# python3 -m pip install --user pipx
pipxensurepath
# Install isolated global tools
pipxinstallblack
pipxinstallhttpie
pipxinstallpoetry
# Use the tool anywhere
black--version
httphttps://api.github.com
Troubleshooting
The environment does not activate
The activation script only changes variables of the current shell, including PATH and VIRTUAL_ENV. Launched as a program (./activate instead of source), it runs in a subshell that disappears immediately: no error, no effect. So check how you call the script before suspecting the environment itself. The last row of the table matches this case.
Script run without source, or .venv/bin/activate file missing
Use source .venv/bin/activate; check that the file exists
Swipe to see more
pip installs globally despite activation
Two causes cover almost every case. The first is sudo: it replaces your PATH with the secure_path defined in /etc/sudoers. With the default configuration of most distributions, sudo pip installignores the active environment and writes to the system packages.
The second is a moved or renamed environment. The .venv/bin/pip launcher is a script whose shebang (the first line, which designates the interpreter) contains the absolute path of the interpreter, fixed at creation. If you move the project directory, this path becomes invalid and you get cannot execute: required file not found. Recreate the environment then: it cannot be repaired. The check with the full path below tells the two situations apart without depending on PATH.
/path/to/.venv/bin/pip
# Check which pip is used
whichpip
# If it does not, use it explicitly
.venv/bin/pipinstallrequests
Version conflict during installation
pip install agrees to break an existing dependency: it prints an ERROR: pip's dependency resolver does not currently take into account all the packages that are installed line, then ends with Successfully installed and returns exit code 0. A CI pipeline that only looks at that code sees nothing. pip check rereads the metadata of the packages already present afterwards and reports unmet requirements. Run it after each series of installations: the output No broken requirements found. is the only acceptable result before freezing a requirements.txt.
Terminal window
# See conflicting dependencies
pipcheck
# Force the reinstallation of the dependencies
pipinstall--force-reinstall-rrequirements.txt
The environment is corrupted
Sometimes, after a system Python update, the environment stops working:
Terminal window
# Solution: recreate the environment
rm-rf.venv
python3-mvenv.venv
source.venv/bin/activate
pipinstall-rrequirements.txt
Key takeaways
If you remember only six things from this guide, remember these:
Always use a virtual environment, even for a small project.
The .venv convention, name your environment .venv in the project directory. Since Python 3.13, venv excludes it from Git on its own with a .gitignore placed in the directory; before that, add .venv/ to the project's .gitignore.
Activate before installing, check that (.venv) appears in your prompt before any pip install.
requirements.txt for reproducibility, export with pip freeze > requirements.txt and version this file.
deactivate to get out, simple but often forgotten. Your prompt goes back to normal.
Deleting = deleting the directory, no complicated uninstall, just rm -rf .venv.
Knowledge check
Check that you have grasped the essentials of this guide. The questions cover
only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
6 questions
6 min
70% to pass
How it works
The timer starts when you click Start
Multiple choice, true/false and short answer questions
You can move between questions
Detailed results are shown at the end
Starts the quiz and the timer
⏱️--:--
0 / 6
Review
(0/0)
--:--
0%
0Correct
0To review
0:00Time
-Level
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Continue the course: pytest: write and run Python tests
A new full quiz with random questions
Work again only on the questions you missed
Checklist
Use this checklist to validate your mastery of virtual environments:
Basics
These four steps form the complete cycle of an environment. Do them in order in an empty directory: if which python still returns the system Python after activation, stop there, everything that follows in this guide would rest on an activation that did not take.
Create an environment with python3 -m venv .venv
Activate the environment (Linux/macOS/Windows)
Check the activation with which python
Deactivate with deactivate
Package management
The point that really makes the difference is the last one. Until you have replayed pip install -r requirements.txt in a new environment, you do not know whether your dependency file is complete; a package installed by hand and forgotten in the export only shows up when a colleague clones the project.
Install a package with pip install
Install a specific version
List installed packages with pip list
Export with pip freeze > requirements.txt
Install from pip install -r requirements.txt
Advanced
These four points are about project hygiene rather than how it works. The third is the one most often skipped: installing a command-line tool such as black or httpie with pip inside the project makes it unavailable elsewhere and adds it to requirements.txt although it is not part of the application's dependencies. pipx separates the two uses.