This article explains why a cimg/python convenience image may report an unexpected Python version, and how to ensure your build uses the correct interpreter.
Problem
You specify a cimg/python image (e.g., cimg/python:3.11) but your build runs a different Python version, or packages you installed are not found at runtime.
Example symptoms:
$ python3 --version Python 3.x.x (different from the version you expected)
ModuleNotFoundError: No module named 'your_package'
Cause
The cimg/python images provide the requested Python version through pyenv, a Python version manager. The underlying base image also includes a separate system Python at a different version. These are two separate interpreters.
Common ways to accidentally use the system Python instead of pyenv:
Installing Python packages with
apt-get(e.g.,sudo apt-get install python3-pip). These packages are installed for the system Python only.Running pip with
sudo(e.g.,sudo pip3 install ...).sudobypasses pyenv and uses the system Python's pip.A
.python-versionfile in your repo that references a version not installed in pyenv. Pyenv will fall back to the system Python.
Solution
apt-get / sudo pip pattern
Install Python packages with pip install (no sudo) instead of apt-get or sudo pip3. This routes through pyenv and installs under the correct Python version.
Before (broken):
- run:
name: Install dependencies
command: |
sudo apt-get install python3-pip python3-dev
sudo pip3 install -r requirements.txtAfter (fixed):
- run:
name: Install dependencies
command: |
pip install -r requirements.txtFor packages that need C libraries to compile, install the C library via apt-get but install the Python package via pip:
- run:
name: Install dependencies
command: |
sudo apt-get update && sudo apt-get install -y <library-dev-package>
pip install <python-package>You do not need to install python3-pip, python3-dev, or python3-setuptools via apt-get. The pyenv Python already includes pip, setuptools, and development headers.
.python-version fallback
If your repository contains a .python-version file that specifies a version not installed in pyenv, either:
Update the file to match the version installed in the image
Remove the file for CI
Pin your image to the exact patch version in your config
Verification
Run which python3 and python3 --version to confirm the correct interpreter is active.
- run:
name: Verify Python version
command: |
which python3
python3 --versionIf which python3 points to the system path, your steps are using the system Python instead of pyenv. The pyenv-managed Python will show a different path.