Python powers web frameworks like Django and Flask, automation scripts, and data applications. This guide covers installing Python, pip, and virtual environments — the standard workflow for isolating project dependencies.
Prerequisites
- Ubuntu 22.04/24.04 or Debian 11/12 VPS
- Root or sudo access
Step 1 — Check the Pre-Installed Version
python3 --version
Ubuntu and Debian ship with Python 3 by default, though possibly not the latest release.
Step 2 — Install Python and Essential Tools
sudo apt update
sudo apt install python3 python3-pip python3-venv -y
Step 3 — Verify pip
pip3 --version
Step 4 — Installing a Newer Python Version (If Needed)
For a version not available in the default repositories, use the deadsnakes PPA (Ubuntu only):
sudo add-apt-repository ppa:deadsnakes/ppa -y
sudo apt update
sudo apt install python3.12 python3.12-venv -y
Step 5 — Create a Virtual Environment
python3 -m venv myproject-env
Step 6 — Activate the Virtual Environment
source myproject-env/bin/activate
Your shell prompt will show the environment name, confirming it's active.
Step 7 — Install Packages Inside the Virtual Environment
pip install requests flask
Step 8 — Deactivate When Done
deactivate
Why Virtual Environments Matter
Without one, all packages install system-wide, causing version conflicts between different projects requiring different library versions. Every project should have its own isolated environment.
Managing Dependencies with requirements.txt
Export your project's exact dependencies:
pip freeze > requirements.txt
Install from that file on another machine/server:
pip install -r requirements.txt
Running a Test Script
echo "print('Hello from Python')" > hello.py
python3 hello.py
Common Errors
"externally-managed-environment" error installing with pip — recent Ubuntu/Debian versions block system-wide pip installs by default; use a virtual environment instead (the recommended approach) rather than bypassing this protection.
"python: command not found" — use python3 explicitly; the bare python command isn't guaranteed to exist on Debian-based systems.
Best Practices
- Always use a virtual environment per project
- Keep a
requirements.txtfile in version control for reproducible installs - Avoid installing packages system-wide with
sudo pip
Related Articles
- How to Deploy a Django/Flask Application with Gunicorn and Nginx
- How to Install Nginx on Ubuntu & Debian
- How to Schedule Tasks with Cron on a Linux VPS
