Skip to content
Latchkey

Python "ModuleNotFoundError: No module named '_bz2'" in CI

The interpreter was compiled without bzip2 (or lzma) development headers, so the _bz2/_lzma extension was skipped. Reading .bz2/.xz data - or some pandas/datasets paths - then fails at runtime.

What this error means

Code that decompresses bzip2 or xz data fails with ModuleNotFoundError: No module named '_bz2' (or _lzma). Plain text and other formats work; only the missing compression extension breaks.

Python traceback
ModuleNotFoundError: No module named '_bz2'
# common trigger:
import bz2  # or a library reading a .bz2 / .xz file

Common causes

bzip2/lzma headers missing at build time

Compiling CPython without libbz2-dev (or liblzma-dev) skips _bz2/_lzma. The interpreter cannot decompress those formats.

A from-source/pyenv build on a slim image

Minimal images lack the compression dev libraries, so a from-source interpreter is missing these modules until the headers are added and Python is rebuilt.

How to fix it

Install compression headers and rebuild

Terminal
# Debian/Ubuntu
apt-get update && apt-get install -y libbz2-dev liblzma-dev
pyenv install 3.12.4

Or use a prebuilt interpreter

A distro or hosted-CI interpreter ships the full set of stdlib compression modules.

.github/workflows/ci.yml
- uses: actions/setup-python@v5
  with:
    python-version: '3.12'

How to prevent it

  • Install the full CPython build-dep set (incl. libbz2-dev, liblzma-dev) before from-source builds.
  • Prefer prebuilt interpreters in CI.
  • Smoke-test import bz2, lzma after building an interpreter.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →