Python virtual environments isolate project dependencies, preventing version conflicts between projects. Ubuntu 24.04 LTS ships with Python 3.12 and the built-in venv module. This guide covers creating and managing virtual environments.

Tested and valid on:

  • Ubuntu 24.04 LTS

Prerequisites

  • Ubuntu 24.04 LTS
  • Python 3.12 installed
  • A user account

Step 1 – Install the venv Module

Ensure the venv module is available:

sudo apt install python3.12-venv -y

Step 2 – Create a Virtual Environment

Create a new virtual environment in your project directory:

mkdir ~/myproject && cd ~/myproject
python3.12 -m venv venv

Step 3 – Activate the Virtual Environment

Activate it:

source venv/bin/activate

Your shell prompt will change to show (venv).

Step 4 – Install Packages

Install packages into the isolated environment:

pip install flask requests pandas

Step 5 – Save Dependencies

Create a requirements file:

pip freeze > requirements.txt

Step 6 – Recreate an Environment from requirements.txt

On another machine or after a fresh clone:

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

Step 7 – Deactivate and Remove

Deactivate the current environment:

deactivate

Remove it entirely by deleting the directory:

rm -rf venv

Step 8 – Use pipx for Standalone Tools

For command-line Python tools (like Black, Ansible), use pipx instead of venv:

sudo apt install pipx -y
pipx install black

Conclusion

Virtual environments are a best practice for Python development on Ubuntu 24.04 LTS. Every project should have its own isolated environment to avoid dependency conflicts.