Skip to content

How to Use Python Virtual Environments (venv) on Debian & Ubuntu

How to Use Python Virtual Environments (venv) on Debian & Ubuntu

Python virtual environments allow you to create isolated environments for different projects, keeping dependencies separate and avoiding conflicts between projects. This guide will show you how to create and manage virtual environments on Debian and Ubuntu.


Prerequisites

  • Python 3.3 or later (included in Ubuntu by default)
  • Terminal access
Note: Python 3.3+ includes venv natively – no additional installation needed!

Creating a Virtual Environment

Step 1: Navigate to Your Project Directory

cd ~/myproject
# or wherever your project is located

Step 2: Create the Virtual Environment

python3 -m venv myenv

Replace myenv with your preferred environment name. A new directory will be created.


Activating the Virtual Environment

Bash / Zsh:

source myenv/bin/activate

You’ll see the environment name in your terminal prompt:

(myenv) user@hostname:~/myproject$
Success! The virtual environment is now active. Any packages you install will be isolated to this environment.

Installing Packages

With the environment activated, use pip to install packages:

pip install requests
pip install flask
pip install django

Install from requirements.txt:

pip install -r requirements.txt

List installed packages:

pip list

Deactivating the Virtual Environment

deactivate

You’ll return to the system Python.


Deleting a Virtual Environment

Simply remove the directory:

rm -rf myenv

Best Practices

  • Name consistently: Use venv, .venv, or env for all projects
  • Add to .gitignore: Don’t commit the venv directory
  • Use requirements.txt: Export all dependencies
  • One venv per project: Keep projects isolated

Common Commands Cheat Sheet

# Create environment
python3 -m venv myenv

# Activate (Linux/Mac)
source myenv/bin/activate

# Activate (Windows)
myenv\Scripts\activate.bat

# Install package
pip install package-name

# Export requirements
pip freeze > requirements.txt

# Install from requirements
pip install -r requirements.txt

# Deactivate
deactivate

# Delete environment
rm -rf myenv

Troubleshooting

Python Not Found

Install Python 3:

sudo apt update
sudo apt install python3 python3-pip

Permission Denied

Don’t use sudo with pip in a virtual environment:

# Wrong:
sudo pip install requests

# Correct:
pip install requests

pip Upgrade

If pip is outdated:

pip install --upgrade pip

Congratulations! You now know how to use Python virtual environments. Your projects will stay clean and dependency-free!