Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Install Python on Ubuntu

By Kokil Thapa | Last reviewed: September 2026

You need to install Python on Ubuntu before you can run automation scripts, data tools, or AI integrations on a server. Ubuntu ships Python 3 in its repositories, but the default version may not match your project. On production Ubuntu 22.04 and 24.04 LTS boxes I maintain alongside PHP and Laravel stacks, Python often arrives as a dependency for deployment tools, monitoring agents, or client automation—not as the main application runtime. This guide walks through apt, the deadsnakes PPA, and pyenv so you pick the right path and avoid breaking system tools that rely on the distro Python.

What is the best way to install Python on Ubuntu?

There is no single winner. The best method depends on whether Python is a system dependency or your primary runtime. Ubuntu expects /usr/bin/python3 to stay stable. Replacing it with a custom build can break apt, cloud-init, and unattended upgrades.

For most server work—cron scripts, small utilities, CI runners—use the repository package. For application development that pins a minor version, use deadsnakes or pyenv. For teams juggling many projects, pyenv plus per-project virtual environments is the cleanest long-term setup.

Install Python on Ubuntu — Method PickerWhat is your goal?Scripts, tools, or pinned app versionapt installSystem scripts, apt toolsdeadsnakes PPASpecific 3.x on LTSpyenvMany versions per userAlways use venvNever pip into systempython3.12 -m venvSide-by-side binariespyenv local 3.12.4Per-project pinning
Decision flow for install Python on Ubuntu: apt for system use, deadsnakes or pyenv when you need a pinned minor version.
MethodBest forProsCons
apt install python3Server scripts, apt-managed toolsFast, security updates via UbuntuVersion tied to release; may lag upstream
deadsnakes PPAOne extra 3.x on LTS without pyenvClean packages, easy uninstallPPA trust; not every micro-release
pyenvDevelopers, many projects, CI-like parityAny CPython version per directoryBuild deps; compile time on first install
Source compileCustom builds, embedded systemsFull control over flagsManual patching; you own upgrades

I treat Python on Ubuntu servers the same way I treat PHP version management: keep the system interpreter alone, isolate application dependencies, and document which binary each cron job uses. That pattern matches how I run mixed stacks described in our Linux system administration work and on booking platforms like Adventure Third Pole Trek where Python utilities sit next to Laravel services.

How do you install Python 3 from apt on Ubuntu?

The fastest path to install Python on Ubuntu is the default repository. Ubuntu 24.04 LTS ships Python 3.12; Ubuntu 22.04 LTS ships Python 3.10. Both are fine for general scripting if your libraries support them.

Step 1: Update package indexes

Refresh indexes before installing anything. Stale metadata causes confusing "package not found" errors.

sudo apt update
sudo apt upgrade -y

See what apt update actually does if you want the mechanics behind that command.

Step 2: Install Python and tooling

sudo apt install -y python3 python3-venv python3-pip python3-dev

The python3-dev package headers are required when pip builds wheels from source—common with older libraries on fresh servers.

Step 3: Verify the install

python3 --version
which python3
pip3 --version

Expected output on Ubuntu 24.04 looks like Python 3.12.x. On 22.04 you should see Python 3.10.x.

Step 4: Install the venv package explicitly on minimal images

Ubuntu Server minimal installs sometimes omit python3-venv. Without it, python3 -m venv fails with a clear but annoying error about ensurepip.

sudo apt install -y python3-venv
python3 -m venv ~/venvs/demo
source ~/venvs/demo/bin/activate
python --version

Never run sudo pip install into the system site-packages. That breaks apt-managed Python modules and creates undeclared dependencies. Use a virtual environment for every project, the same way you would isolate Node versions after you install Node.js on Ubuntu.

apt Install Python on Ubuntu — Core Steps1. apt updateRefresh indexes2. apt installpython3 + venv + pip3. Verifypython3 --version4. venvIsolate depsWhich version do you need?Distro default → stop at step 4 with venvPinned 3.11 / 3.12 → deadsnakes or pyenv belowDo not replace /usr/bin/python3 on production servers
Standard apt workflow to install Python on Ubuntu: update, install packages, verify, then create a virtual environment before pip installs.

How do you install multiple Python versions on Ubuntu?

When your app requires Python 3.12 but the server runs 22.04 with 3.10, add a parallel interpreter. Two reliable options exist: the deadsnakes PPA and pyenv.

The deadsnakes PPA publishes newer CPython builds for supported Ubuntu LTS releases. Install Python 3.12 on Ubuntu 22.04 like this:

sudo apt install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install -y python3.12 python3.12-venv python3.12-dev

python3.12 --version
python3.12 -m venv ~/venvs/myapp-312
source ~/venvs/myapp-312/bin/activate

Binaries land as python3.12, not as a replacement for python3. System tools keep using the distro default. That is exactly what you want on a web server also running Apache, PHP-FPM, and MySQL—you do not want apt pulling packages against the wrong interpreter.

Manage PPA trust carefully. Only add PPAs you expect to maintain. Document them in your server runbook alongside other repos from our Ubuntu repository management guide.

pyenv installs CPython under your home directory and switches versions per shell or per project directory.

  1. Install build dependencies:
sudo apt install -y build-essential libssl-dev zlib1g-dev \
  libbz2-dev libreadline-dev libsqlite3-dev curl \
  libncursesw5-dev xz-utils tk-dev libxml2-dev \
  libxmlsec1-dev libffi-dev liblzma-dev
  1. Install pyenv via the official installer script from the pyenv GitHub repository.
  2. Add pyenv to your shell startup file.
  3. Install and select a version.
curl https://pyenv.run | bash

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
source ~/.bashrc

pyenv install 3.12.4
pyenv global 3.12.4
python --version

For per-project pinning, run pyenv local 3.12.4 inside the repo root. That writes a .python-version file teammates and CI can read.

On shared production servers I prefer deadsnakes over pyenv. Package names are explicit in Ansible or shell scripts. pyenv shines on developer laptops and build agents where you mirror production loosely.

How do you set up pip and a virtual environment on Ubuntu?

Installing Python is half the job. Isolating dependencies with venv is what keeps servers predictable.

Create and activate a venv

mkdir -p ~/projects/my-api && cd ~/projects/my-api
python3.12 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install requests fastapi uvicorn

Your prompt should show (.venv). While active, python and pip point inside the project—not at system paths.

Freeze dependencies for deployment

pip freeze > requirements.txt

On the server or in CI, recreate the environment:

python3.12 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Pair this with a systemd unit that calls the venv binary directly:

ExecStart=/home/deploy/my-api/.venv/bin/uvicorn main:app --host 127.0.0.1 --port 8001

That avoids activation scripts in service definitions. It is the same pattern I use when documenting cron paths—always use absolute paths to the interpreter, as covered in our Ubuntu cron jobs guide.

If you exchange JSON between a Python microservice and a Laravel API, validate payloads during development with the site JSON formatter tool before wiring production webhooks.

venv Isolation After You Install Python on UbuntuSystem Python/usr/bin/python3apt packages onlycloud-init, apt, unattended-upgradesNo sudo pip installProject venv.venv/bin/pythonpip install -r requirements.txtFastAPI, pandas, boto3Safe to upgrade pipisolatedsystemd ExecStart uses .venv/bin/ path — not shell activate
Virtual environments keep project pip packages away from Ubuntu system Python after you install Python on Ubuntu.

How do you install Python for Docker and CI on Ubuntu?

Containers shift the question. On the host you may only need Python for docker-compose helpers. Inside images you pick a base and install during build.

Host Ubuntu: minimal Python for tooling

sudo apt install -y python3 python3-pip
pip3 install --user docker-compose

Prefer the Compose V2 plugin via apt install docker-compose-v2 when available. It removes the separate Python dependency entirely.

Inside Dockerfile: use official slim images

FROM python:3.12-slim-bookworm
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["gunicorn", "app:application", "-b", "0.0.0.0:8000"]

Build on Ubuntu CI runners with Docker installed per our Docker on Ubuntu guide. Pin the image tag—python:3.12-slim today, not python:latest six months from now.

For GitLab CI on Ubuntu runners, cache the venv or use multi-stage builds. Commit a .python-version or document the deadsnakes package name in your deploy README so the next engineer knows which binary cron and systemd expect.

How do you troubleshoot common Python installation problems on Ubuntu?

Most failures fall into a short list. Fix them in this order before reinstalling everything.

  • python3: command not found — Python is not installed or PATH is wrong. Run sudo apt install python3 and check echo $PATH.
  • externally-managed-environment on pip install — PEP 668 on Ubuntu 23.04+ blocks system-wide pip. Use a venv or pip install --user for ad-hoc tools.
  • ensurepip is not available — Install python3-venv or python3.12-venv for your target version.
  • Wrong interpreter in cron — Cron uses a minimal PATH. Call /full/path/to/.venv/bin/python explicitly.
  • ModuleNotFoundError in systemd service — Service runs system Python instead of venv. Fix ExecStart to the venv binary.
  • SSL errors during pip — Clock skew or missing CA certs. Run sudo apt install ca-certificates and verify NTP.

Fix the externally-managed-environment error

Ubuntu marks the system Python as externally managed to protect apt. The correct fix is a venv:

python3 -m venv ~/venvs/tools
source ~/venvs/tools/bin/activate
pip install httpx

Do not delete /usr/lib/python3.*/EXTERNALLY-MANAGED on production servers. You will regret it at the next dist-upgrade.

Register alternatives when multiple python3 binaries exist

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 2
sudo update-alternatives --config python3

Use alternatives only when you understand the blast radius. On web servers I leave python3 pointing at the distro default and call python3.12 explicitly in app configs.

Install Python on Ubuntu — Common Gotchasexternally-managed-environmentpip blocked on system PythonFix: python3 -m venvcron ModuleNotFoundErrorwrong PATH in crontabFix: full .venv/bin/python pathensurepip missingminimal server imageFix: apt install python3-venvreplaced system python3apt or cloud-init breaksFix: reinstall distro python3
Typical errors after you install Python on Ubuntu and the fixes: venv for pip blocks, absolute paths for cron, package installs for ensurepip.

When Python shares a box with MySQL, Nginx, and PHP-FPM, document every interpreter path in your runbook. Mixed stacks fail silently when a backup script upgrades its venv but cron still calls yesterday's binary. Server setup checklists in our Ubuntu server setup guide and web server hardening article include the same "absolute paths everywhere" rule.

How do you keep Python updated and secure on Ubuntu?

Security patches for distro Python arrive through unattended-upgrades or your normal apt maintenance window. Track CVE notices for CPython via the official Python documentation and Ubuntu security announcements.

sudo apt update
sudo apt install --only-upgrade python3 python3-minimal
python3 --version

For deadsnakes packages, run apt upgrades on the same schedule as the rest of the server. For pyenv-managed interpreters, run pyenv install for patched micro releases and update .python-version files in repos.

Apply the same discipline as other services: restrict outbound network if the app does not need it, run services as unprivileged users, and keep SSH hardened per our Ubuntu security hardening guide. If Python automation touches client infrastructure, fold upgrades into a support and maintenance retainer so venv rebuilds and dependency audits happen on a calendar—not after an incident.

On Nepali business servers where uptime windows are narrow around Dashain and Tihar, schedule Python package updates during low-traffic hours. Test pip install -r requirements.txt in staging first. Breaking changes in transitive dependencies cause more downtime than interpreter patch bumps.

Key Takeaways

  • Install Python on Ubuntu with apt install python3 python3-venv python3-pip for scripts and system tools—leave /usr/bin/python3 alone.
  • Use deadsnakes or pyenv when you need a pinned minor version; call python3.12 explicitly instead of replacing the default.
  • Always create a virtual environment before pip install; never use sudo pip on production servers.
  • Point systemd and cron at full venv binary paths to avoid ModuleNotFoundError surprises.
  • Treat PEP 668 "externally-managed-environment" as a feature—fix it with venv, not by deleting protection files.
  • Document interpreter paths in deploy runbooks alongside other stack versions from PHP and MySQL installs on the same host.

People Also Ask

Does Ubuntu come with Python pre-installed?

Yes. Ubuntu desktop and server images include Python 3 because system tools depend on it. Run python3 --version to see the default. Minimal cloud images may omit python3-pip and python3-venv, so install those packages explicitly before building environments.

Should I use python or python3 on Ubuntu?

Always use python3 in scripts and documentation. Ubuntu does not guarantee a python command points to Python 3 unless you create one inside a venv. Inside an activated venv, python is safe because it refers to the isolated interpreter.

Is the deadsnakes PPA safe for production servers?

It is widely used on Ubuntu LTS for extra CPython versions and keeps packages separate from the system default. Treat it like any third-party repository: pin versions, test upgrades in staging, and prefer venvs for application dependencies rather than system-wide pip installs.

What Python version should I use on Ubuntu in 2026?

For new projects, target Python 3.12 or newer if your libraries support it. Ubuntu 24.04 ships 3.12; 22.04 ships 3.10 with 3.12 available via deadsnakes. Check your framework's support matrix before upgrading production interpreters.

Next steps after you install Python on Ubuntu

You now have a working interpreter, an isolated venv workflow, and a clear rule: system Python stays clean, project Python lives in .venv. That is the same discipline I apply when provisioning Ubuntu boxes for Laravel, WordPress, and automation sidecars—boring, repeatable, easy for the next developer to inherit.

If you are standing up a mixed stack and want someone to handle Python utilities, PHP apps, cron, and hardening on one server, review the AI integration and automation service or browse the portfolio for examples of production systems shipped end to end. For hands-on help with Ubuntu server setup, environment variables, or shell automation, read the environment variables guide and shell scripting tutorial next—or contact us to talk through your server layout.

Frequently Asked Questions

There is no single winner—it depends on your use case. For server scripts, cron jobs, and apt-managed tools, use sudo apt install python3 python3-venv python3-pip and leave /usr/bin/python3 alone. When you need a pinned minor version alongside the distro default, add deadsnakes for one extra release or pyenv for many. I treat Python on production Ubuntu boxes the same way I manage PHP versions: system interpreter stays untouched, application code runs inside isolated virtual environments with documented binary paths.

Run sudo apt update, then sudo apt install -y python3 python3-venv python3-pip python3-dev. The python3-dev headers matter when pip compiles wheels from source. Verify with python3 --version, which python3, and pip3 --version. Ubuntu 24.04 LTS ships Python 3.12; 22.04 LTS ships 3.10. On minimal server images, install python3-venv explicitly before running python3 -m venv, then activate the environment before any pip install. Never run sudo pip into system site-packages.

Yes. Desktop and server images include Python 3 because system tools depend on it. Run python3 --version to check. Minimal cloud images may omit python3-pip and python3-venv.

Always use python3 in scripts and docs. Ubuntu does not guarantee python points to Python 3. Inside an activated venv, python is safe.

Two reliable paths exist. For one extra version on LTS, add the deadsnakes PPA: sudo add-apt-repository ppa:deadsnakes/ppa, then sudo apt install python3.12 python3.12-venv python3.12-dev. Binaries land as python3.12 without replacing python3. For developers juggling many releases, install pyenv with build dependencies, run the official installer from the pyenv GitHub repo, add it to ~/.bashrc, then pyenv install 3.12.4. On shared production servers I prefer deadsnakes; pyenv suits laptops and CI agents.

From your project directory, run python3.12 -m venv .venv, source .venv/bin/activate, pip install --upgrade pip, then install packages. Your prompt shows (.venv) while active. Freeze dependencies with pip freeze > requirements.txt and recreate on the server with pip install -r requirements.txt inside a fresh venv. For systemd services, point ExecStart at the full venv binary path—for example /home/deploy/my-api/.venv/bin/uvicorn—instead of relying on shell activation scripts.

It is widely used on Ubuntu LTS for parallel CPython versions and keeps packages separate from the system default. Treat it like any third-party repository: document it in your server runbook, pin versions, test upgrades in staging, and install application dependencies inside venvs rather than system-wide pip. On web servers also running Apache, PHP-FPM, and MySQL, calling python3.12 explicitly avoids apt pulling packages against the wrong interpreter.

Target Python 3.12 or newer for new projects if your libraries support it. Ubuntu 24.04 ships 3.12; 22.04 ships 3.10 with 3.12 available via deadsnakes.

Ubuntu marks system Python as externally managed under PEP 668 to protect apt. Create a virtual environment: python3 -m venv ~/venvs/tools, source it, then pip install your packages. Do not delete /usr/lib/python3.*/EXTERNALLY-MANAGED on production servers—you will regret it at the next dist-upgrade. For ad-hoc single-user tools, pip install --user is acceptable, but venv is the correct long-term fix for anything you maintain.

You should not replace /usr/bin/python3 with a custom build. Ubuntu expects the distro Python to stay stable; changing it can break apt, cloud-init, and unattended upgrades. If you use update-alternatives to switch between python3.10 and python3.12, understand the blast radius first. On web servers I leave python3 at the distro default and call python3.12 explicitly in app configs, cron jobs, and systemd units—the same absolute-path discipline I apply to PHP binaries on mixed stacks.

Install build dependencies first: build-essential, libssl-dev, zlib1g-dev, libffi-dev, and related dev packages via apt. Run curl https://pyenv.run | bash, then add PYENV_ROOT, PATH, and eval "$(pyenv init -)" to ~/.bashrc and source it. Install a version with pyenv install 3.12.4, set pyenv global 3.12.4 for your user, or pyenv local 3.12.4 inside a repo to write a .python-version file teammates and CI can read. First install compiles CPython, so expect compile time and disk use on fresh servers.

Ubuntu Server minimal images sometimes omit the venv package for your target Python version. Install it explicitly: sudo apt install -y python3-venv for the distro default, or python3.12-venv when using deadsnakes. Without that package, ensurepip cannot bootstrap pip inside the new environment. After installing the venv package, rerun python3 -m venv ~/venvs/demo, activate it, and confirm python --version before installing anything with pip.

Point ExecStart at the full path to the venv binary, not the system python3. Example: ExecStart=/home/deploy/my-api/.venv/bin/uvicorn main:app --host 127.0.0.1 --port 8001. This avoids ModuleNotFoundError when the service runs outside an activated shell. The same rule applies to cron: cron uses a minimal PATH, so always call /full/path/to/.venv/bin/python in crontab entries. Document every interpreter path in your deploy runbook alongside PHP and MySQL versions on mixed hosts.

On the host, you may only need minimal Python for docker-compose helpers: sudo apt install python3 python3-pip, though apt install docker-compose-v2 removes that dependency when available. Inside Dockerfiles, use pinned official slim images like FROM python:3.12-slim-bookworm, copy requirements.txt, run pip install --no-cache-dir -r requirements.txt, and avoid python:latest tags. On GitLab CI Ubuntu runners, cache the venv or use multi-stage builds. Commit a .python-version or document the deadsnakes package name so the next engineer knows which binary cron and systemd expect.

Distro Python security patches arrive through sudo apt update and sudo apt install --only-upgrade python3 python3-minimal. Track CVE notices via official Python documentation and Ubuntu security announcements. For deadsnakes packages, upgrade on your normal apt maintenance schedule. For pyenv interpreters, install patched micro releases and update .python-version files in repos. Test pip install -r requirements.txt in staging before production—transitive dependency breaks cause more downtime than interpreter patches. On Nepali business servers, schedule updates outside Dashain and Tihar peak traffic when uptime windows are narrow.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: