All posts

Fix NotFoundError in Python in Production

Resolve FileNotFoundError and ModuleNotFoundError in production Python deployments, covering path issues, missing packages, and Docker builds.

Python NotFoundError in Production

Python's FileNotFoundError and ModuleNotFoundError in production usually stem from path differences between development and deployed environments.

File Paths

Hardcoded relative paths break when the working directory changes:

# BAD — relative to wherever the process starts
with open('data/config.json') as f:
    config = json.load(f)

# GOOD — relative to the script's location
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
with open(BASE_DIR / 'data' / 'config.json') as f:
    config = json.load(f)

Missing Packages in Docker

# Ensure requirements are installed
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Don't forget system dependencies
RUN apt-get update && apt-get install -y \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

Virtual Environment Issues

# Multi-stage build with venv
FROM python:3.12-slim AS builder
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install -r requirements.txt

FROM python:3.12-slim
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY . /app
WORKDIR /app
CMD ["python", "main.py"]

Import Path Differences

# If running as a module vs script:
# python -m myapp.main  ← correct imports
# python myapp/main.py  ← may break relative imports

Bugsly captures FileNotFoundError with the exact path attempted and ModuleNotFoundError with the import chain, making production path issues immediately diagnosable.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free