Creating a Python virtual environment on Ubuntu isolates project dependencies, preventing package conflicts when multiple projects require different library versions. The virtualenv tool creates self-contained directories with independent Python interpreters and packages, allowing you to maintain clean separation between development environments without affecting the system-wide Python installation.
Virtual environments solve specific development problems: testing new packages without breaking existing projects, maintaining different Django or Flask versions across applications, and ensuring production deployments match development exactly. When you install packages globally with sudo pip, every project shares those versions; upgrading a dependency for one application often breaks another.
This guide explains how to install virtualenv on Ubuntu, create and activate virtual environments, and manage packages safely. It covers the complete workflow from setup to project isolation.
This tutorial covers Ubuntu 26.04 LTS, 24.04 LTS, and 22.04 LTS. The steps are consistent across these releases, though the default Python versions differ (Python 3.13 in Ubuntu 26.04, 3.12 in 24.04, and 3.10 in 22.04). Outputs in this guide reflect Ubuntu 24.04/26.04 environments.
Pre-Installation Steps Before Creating Python Virtual Environment
Update Ubuntu
Refresh your Ubuntu package lists to ensure you install the latest available packages. Open your terminal by pressing Ctrl+Alt+T and run:
sudo apt update
Run apt update to refresh your package index. This ensures you install the latest available versions rather than cached older releases. If you want to upgrade everything after reviewing changes, run sudo apt upgrade. Unattended upgrades can automate security patches for your system.
Install Python (Skip if Installed)
Most Ubuntu installations include Python 3 by default, but minimal container images and cloud instances may omit it. Check for Python by running:
python3 --version
Expected output showing the installed Python version (Ubuntu 24.04 example):
Python 3.12.3
On Ubuntu 26.04, you will see Python 3.13.x. If the command returns “command not found,” install Python:
sudo apt install python3
This installs the default Python 3 version from the Ubuntu repositories (Python 3.13 on Ubuntu 26.04, 3.12 on 24.04, 3.10 on 22.04).
Install Virtual Environment (virtualenv)
The virtualenv package allows you to create isolated environments. While Python includes a built-in module (venv), the standalone virtualenv tool offers speed and extended features. Verify if virtualenv is installed:
virtualenv --version
Expected output:
virtualenv 20.25.0+ds from /usr/lib/python3/dist-packages/virtualenv/__init__.py
If missing, install it with APT:
sudo apt install python3-virtualenv
Choose Your Virtual Environment Tool
Understanding venv vs virtualenv Differences
Python offers two primary tools for isolation: the built-in venv module and the third-party virtualenv package.
The venv module ships with Python 3.3+ and requires only the python3-venv package on Ubuntu. It relies on symlinks and integrates directly with Python’s standard library. This makes it ideal for straightforward project isolation where you need basic, native dependency management.
In contrast, virtualenv offers faster environment creation and richer configuration options. It supports older Python versions and provides features like environment cloning and customizable activation scripts. Choose virtualenv when you need these specific capabilities.
Which Tool Should You Choose?
For most modern projects, venv works perfectly with zero overhead. However, virtualenv remains superior for older Python support and advanced configuration. The table below outlines the key differences:
| Feature | venv (Built-in) | virtualenv (Third-Party) |
|---|---|---|
| Installation | Pre-installed (or python3-venv) | Requires pip or apt install |
| Speed | Fast | Faster (optimized seeding) |
| Python Versions | Same as system Python | Any installed Python version |
| Use Case | Standard projects | Legacy/Complex needs |
This guide covers both methods, starting with virtualenv for its broader feature set, followed by the streamlined venv approach.
Create Virtual Environment with virtualenv
Create the Virtual Environment
Create a new virtual environment by running the virtualenv command followed by your desired directory name:
virtualenv env
In this command, env is the name of the folder that will contain the environment. You can use any name, such as .venv or my_project_env.
Expected output confirming successful creation (Python 3.12 example):
created virtual environment CPython3.12.3.final.0-64 in 224ms
creator CPython3Posix(dest=/tmp/env, clear=False, no_vcs_ignore=False, global=False)
seeder FromAppData(download=False, pip=bundle, via=copy, app_data_dir=/root/.local/share/virtualenv)
added seed packages: pip==24.0
activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
To target a specific Python interpreter version, use the -p flag:
virtualenv -p python3.13 .venv
The -p flag ensures the environment uses a specific Python version. Note: You must have the specified Python version (e.g., Python 3.13) installed on your system before running this command. If it is not installed, install it via APT or the Deadsnakes PPA first.
Common environment names include env, .venv, or venv. Using a dot prefix (.venv) hides the directory in standard file listings.
The directory structure contains:
env/ ├── .gitignore # Automatically excludes __pycache__ directories ├── bin/ # Activation scripts and Python executables ├── lib/ # Python standard library and installed packages └── pyvenv.cfg # Configuration file with Python version info
This isolates your project’s interpreters and libraries from the system.
Activate the Virtual Environment
Activate the environment to start using its isolated interpreter. This adjusts your shell’s path to prioritize the environment’s binaries:
source env/bin/activate
Replace env with your actual directory name.
Confirming Activation
Your terminal prompt will change to show the environment name prefix, indicating the session is active:
(env) joshua@ubuntu-linux:~$
While (env) is visible, any python or pip commands run within this isolated context, protecting your global system packages.
Deactivate the Virtual Environment
Exit the virtual environment to return to the system Python:
deactivate
The prompt prefix disappears, and subsequent commands execute against the system-wide installation. Closing the terminal window also ends the session automatically.
Alternative Method: Using Python’s Built-in venv Module
Python includes the venv module as a built-in tool for creating virtual environments. This offers a lightweight alternative to virtualenv that requires no third-party installation for the tool itself.
Install python3-venv Package
Ubuntu requires the python3-venv package to enable the venv module. Check if it is already installed:
apt list --installed python3-venv
Expected output (Ubuntu 24.04 example):
python3-venv/noble-updates,noble-security,now 3.12.3-0ubuntu2.1 amd64 [installed]
If missing, install it:
sudo apt install python3-venv
Create Virtual Environment with venv
Run the python3 -m venv command followed by your intended environment name:
python3 -m venv myproject
This creates the myproject directory containing the interpreter and pip. The -m flag executes the venv module as a script. Unlike virtualenv, this command runs silently. Verify success by listing the directory contents:
ls -la myproject/
Expected output:
drwxr-xr-x 2 user user 4096 Dec 13 10:40 bin drwxr-xr-x 3 user user 4096 Dec 13 10:40 include drwxr-xr-x 3 user user 4096 Dec 13 10:40 lib lrwxrwxrwx 1 user user 3 Dec 13 10:40 lib64 -> lib -rw-r--r-- 1 user user 153 Dec 13 10:40 pyvenv.cfg
To use a specific installed Python version, call that interpreter directly. Ensure the version is installed first:
python3.13 -m venv .venv
To bootstrap with the latest pip, setuptools, and wheel in one step, add the --upgrade-deps flag:
python3 -m venv --upgrade-deps .venv
The --upgrade-deps flag automatically downloads and installs the newest versions of pip, setuptools, and wheel during environment creation. This is particularly useful on Ubuntu 22.04, where the system pip (version 22.0.2) is significantly older than current releases. Using this flag eliminates the need to run pip install --upgrade as a separate step after activation.
Use the interpreter that matches your project’s Python version requirements to avoid compatibility issues when deploying to production servers.
Activate and Deactivate venv Environments
Activation works identically to virtualenv. Navigate to your project directory and run:
source myproject/bin/activate
Your prompt changes to show the environment name, indicating activation succeeded. To deactivate, use the same deactivate command as with virtualenv.
Verify Active Environment
When working with multiple environments, confirm which one is active using these verification commands:
echo $VIRTUAL_ENV
Expected output showing the full path to your active environment:
/home/username/myproject
If no environment is active, the output will be empty.
Check which Python interpreter you are using:
which python3
Expected output inside an active environment:
/home/username/myproject/bin/python3
This confirms you’re using the environment’s Python binary instead of the system-wide installation at /usr/bin/python3.
To list all packages installed in your active virtual environment, use:
python -m pip list
Expected output showing installed packages (after installing requests):
Package Version ------------------ ---------- certifi 2025.11.12 charset-normalizer 3.4.4 idna 3.11 pip 24.0 requests 2.32.5 urllib3 2.6.2
This displays every package and its version currently installed in the environment, helping you verify the environment’s state and track dependencies.
Managing Python Packages in Virtual Environments
Check pip Availability
Virtual environments created with virtualenv or python3 -m venv include pip by default. After activating your environment, confirm pip is present:
python -m pip --version
Expected output showing pip version and location:
pip 24.0 from /home/username/myproject/lib/python3.12/site-packages/pip (python 3.12)
If this fails, install pip system-wide so new environments can seed their own copy:
sudo apt install python3-pip
Update pip After Activation
After creating a virtual environment, the pip version matches your system’s default package version. Ubuntu 24.04 includes pip 24.0, while Ubuntu 22.04 ships with the older pip 22.0.2. Upgrading pip, setuptools, and wheel ensures you have the latest package installation tools with recent bug fixes and performance improvements:
python -m pip install --upgrade pip setuptools wheel
Expected output showing the upgrade process:
Collecting pip
Downloading pip-25.3-py3-none-any.whl (1.8 MB)
Collecting setuptools
Downloading setuptools-80.9.0-py3-none-any.whl (1.3 MB)
Collecting wheel
Downloading wheel-0.45.1-py3-none-any.whl (72 kB)
Installing collected packages: wheel, setuptools, pip
Attempting uninstall: pip
Found existing installation: pip 24.0
Uninstalling pip-24.0:
Successfully uninstalled pip-24.0
Successfully installed pip-25.3 setuptools-80.9.0 wheel-0.45.1
The setuptools package provides build tools for Python projects, while wheel enables installation of pre-built binary packages instead of compiling from source. Upgrading all three together prevents compatibility issues when installing complex dependencies.
Install a Python Package
Install project dependencies from inside the active environment so nothing leaks into the system site packages. Replace <package_name> with the library you need:
python -m pip install <package_name>
For example, to add requests:
python -m pip install requests
Do not use
sudo pip.On Ubuntu 26.04 and 24.04, running
sudo pip installtriggers an “externally-managed-environment” error (PEP 668) to protect system stability. Even on older versions, using sudo with pip bypasses isolation and can break system tools likenetplanorunattended-upgrades. Always install packages inside your active virtual environment without sudo.
Remove a Python Package
Uninstall packages from the active environment when you no longer need them:
python -m pip uninstall <package_name>
For example, to remove requests:
python -m pip uninstall requests
Expected output prompting for confirmation:
Found existing installation: requests 2.32.5
Uninstalling requests-2.32.5:
Would remove:
/tmp/test_venv/lib/python3.12/site-packages/requests-2.32.5.dist-info/*
/tmp/test_venv/lib/python3.12/site-packages/requests/*
Proceed (Y/n)? y
Successfully uninstalled requests-2.32.5
Pip prompts for confirmation before removing packages. Type y to proceed or n to cancel. Add the -y flag to skip the confirmation prompt in automated scripts: python -m pip uninstall -y requests.
Managing Dependencies with requirements.txt
When collaborating on projects or deploying applications, tracking installed packages ensures everyone works with identical dependencies. Python’s requirements.txt file provides a standard method for documenting and sharing your environment’s exact package versions.
To capture your current environment’s packages, run pip freeze while the environment is active:
python -m pip freeze > requirements.txt
This command lists all installed packages with their versions and writes them to requirements.txt. The file contents look like:
requests==2.32.5
certifi==2025.11.12
charset-normalizer==3.4.4
idna==3.11
urllib3==2.6.2
To replicate this environment on another system or in a fresh virtual environment, install from the requirements file:
python -m pip install -r requirements.txt
This installs every package listed with its specified version, ensuring consistency across development, testing, and production environments.
Run these pip commands only after activating your virtual environment to keep dependencies isolated.
Troubleshooting Common Issues
Error: externally-managed-environment
If you try to run pip install outside a virtual environment on Ubuntu 24.04+, you will see this error:
error: externally-managed-environment
× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.
Cause: PEP 668 protection prevents pip from modifying system packages directly, avoiding conflicts with APT.
Fix: Activate your virtual environment first. Inside a virtual environment, pip has full write access:
source .venv/bin/activate
pip install
Permission Denied in Virtual Environment
If you see “Permission denied” when installing packages:
ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/usr/local/lib/python3.12/dist-packages/...'
Cause: You likely forgot to activate your environment, so pip is trying to write to the system directory which requires root access.
Fix: Do not use sudo. Instead, check your prompt for the (env) prefix. If missing, activate the environment:
source .venv/bin/activate
Error: python3: command not found
If you see this error when checking versions, Python 3 is missing (common in minimal containers):
sudo apt update && sudo apt install python3
Error: ensurepip is not available
When running python3 -m venv, this error indicates the python3-venv package is missing:
Error: Command '['.../bin/python3', '-m', 'ensurepip'...] returned non-zero exit status 1.
Fix it by installing the module:
sudo apt install python3-venv
Virtual Environment Broken After Upgrade
If you upgrade Ubuntu or Python, environments may break because they rely on symlinks to the system interpreter. Errors like unsupported locale setting or missing paths confirm this.
Fix: Delete and recreate the environment:
rm -rf .venv
python3 -m venv .venv
source .venv/bin/activate
# Reinstall dependencies if you have a requirements file
# pip install -r requirements.txt
Virtual Environment Best Practices
Following established conventions ensures your virtual environments remain maintainable and portable across development teams and deployment environments.
Naming Conventions
Use .venv or venv as your environment directory name. The dot prefix hides the directory in file listings on Linux (use ls -la to see hidden directories), reducing clutter in project folders. Many Python tools and IDEs recognize these standard names automatically. For example, Visual Studio Code detects .venv directories and offers to activate them when you open a Python file.
Alternatively, env or project-specific names like myproject-venv work when managing multiple environments in separate directories. Avoid spaces in environment names to prevent issues with shell commands and scripts.
Version Control Exclusion
Never commit virtual environment directories to Git or other version control systems. These directories contain thousands of files specific to your system’s Python installation and take significant repository space. Instead, add your environment directory to .gitignore:
# .gitignore
venv/
.venv/
env/
ENV/
Commit your requirements.txt file instead, letting team members recreate the environment locally with python -m pip install -r requirements.txt.
Environment Recreation
Treat virtual environments as disposable infrastructure, not precious artifacts. If an environment becomes corrupted or accumulates unnecessary packages from testing, delete the directory and recreate it from your requirements.txt. This takes seconds and guarantees a clean state matching your documented dependencies:
rm -rf .venv
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
This workflow is faster than debugging strange package conflicts or figuring out which experimental packages to uninstall. Regular recreation also catches missing dependencies. If your requirements.txt is incomplete, the fresh environment will reveal gaps immediately rather than working accidentally because packages remained from earlier testing.
Common Virtual Environment Workflows
Understanding typical virtual environment usage patterns helps you apply these tools effectively in real projects.
New Project Setup
When starting a new Python project, establish the virtual environment first:
mkdir myproject
cd myproject
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install requests flask
python -m pip freeze > requirements.txt
This creates a project directory, initializes a virtual environment, upgrades pip, installs your initial dependencies, and captures them in requirements.txt. The requirements file becomes part of your project’s version control, documenting exactly which packages your application needs.
Cloning an Existing Project
When working with a project that includes a requirements.txt file (if you need Git on Ubuntu, install it first):
git clone https://github.com/user/project.git
cd project
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
This pattern ensures you match the project’s documented dependencies exactly. The virtual environment remains local to your clone. Other developers working on the same project maintain their own isolated environments with identical packages.
Working Across Multiple Projects
When switching between projects, deactivate the current environment before activating another:
# Working on project A
cd ~/projects/project-a
source .venv/bin/activate
python manage.py runserver
deactivate
# Switching to project B
cd ~/projects/project-b
source .venv/bin/activate
python app.py
Each project maintains its own environment with independent package versions. Project A might use Django 4.2 while Project B uses Django 5.0. Virtual environments prevent version conflicts between these incompatible dependencies.
Remove Python Virtual Environment Tools
If you no longer need virtual environment capabilities on your system, remove the installed packages and clean up any created environments.
Remove virtualenv Package
Uninstall the virtualenv package from your system:
sudo apt remove --purge python3-virtualenv
The --purge flag removes configuration files in addition to the package itself. After removing virtualenv, clean up any automatically installed dependencies:
sudo apt autoremove
This command removes packages that were installed as dependencies for virtualenv but are no longer needed by any other software.
Remove python3-venv Package
If you installed the python3-venv package for the built-in venv module, remove it with:
sudo apt remove --purge python3-venv
Follow this with autoremove to clean up dependencies:
sudo apt autoremove
Delete Virtual Environment Directories
Removing the virtualenv or venv packages does not delete existing virtual environments you created. These remain in your project directories until you manually remove them. To delete a virtual environment directory:
rm -rf /path/to/env
Replace /path/to/env with the actual path to your virtual environment directory. For example, to remove a virtual environment named .venv in your current project:
rm -rf .venv
This permanently deletes the environment directory and all installed packages within it. If you’re using version control, ensure your .gitignore already excludes these directories so you don’t accidentally commit them before removal.
Conclusion
Python virtual environments isolate project dependencies on Ubuntu, preventing package conflicts across projects. The virtualenv tool creates these isolated environments, while pip manages packages within them. Your Ubuntu system now supports multiple Python projects with independent dependency chains, each activated and managed through simple terminal commands.