Using a Different Python Version in a Virtual Environment

Configure a python virtual environment to use a specific python version

By Chi Kit Yeung in Python Cookbook

August 26, 2024

Problem

I had to run a project that strictly required a specific python version (3.9.6) but I had a newer version installed (3.12.4) by default. Thankfully, stackoverflow has the answer. Thank you Daniel Roseman, Mateen Ulhaq, and The Aelfinn on this thread for the solution.

Solution

Specify Python Version from the Start

In your project’s directory:

python3 -m venv "my_env_name"
python3.9 -m venv "my_env_name"

Change Python version after creating the virtual environment

virtualenv --python="/usr/local/bin/python3.9" "/path/to/new/virtualenv/"