pypa/pip · error · ClassNotFound

cannot read {filename}: {err}

Error message

cannot read {filename}: {err}

What it means

Raised by load_lexer_from_file when open(filename) raises OSError (file missing, permission denied, is a directory). The path is relative to the current working directory.

Source

Thrown at src/pip/_vendor/pygments/lexers/__init__.py:162

    is equivalent to running eval on the input file.

    Raises ClassNotFound if there are any problems importing the Lexer.

    .. versionadded:: 2.2
    """
    try:
        # This empty dict will contain the namespace for the exec'd file
        custom_namespace = {}
        with open(filename, 'rb') as f:
            exec(f.read(), custom_namespace)
        # Retrieve the class `lexername` from that namespace
        if lexername not in custom_namespace:
            raise ClassNotFound(f'no valid {lexername} class found in {filename}')
        lexer_class = custom_namespace[lexername]
        # And finally instantiate it with the options
        return lexer_class(**options)
    except OSError as err:
        raise ClassNotFound(f'cannot read {filename}: {err}')
    except ClassNotFound:
        raise
    except Exception as err:
        raise ClassNotFound(f'error when loading custom lexer: {err}')


def find_lexer_class_for_filename(_fn, code=None):
    """Get a lexer for a filename.

    If multiple lexers match the filename pattern, use ``analyse_text()`` to
    figure out which one is more appropriate.

    Returns None if not found.
    """
    matches = []
    fn = basename(_fn)
    for modname, name, _, filenames, _ in LEXERS.values():
        for filename in filenames:

View on GitHub (pinned to d7d0d0a394)

Solutions

  1. Check os.path.isfile before calling.
  2. Use an absolute path built from a known base.
  3. Fix permissions or correct the path.

Example fix

# before
load_lexer_from_file('lexers/mylex.py')  # wrong cwd
# after
import os
base = os.path.dirname(os.path.abspath(__file__))
load_lexer_from_file(os.path.join(base, 'lexers', 'mylex.py'))
Defensive patterns

Strategy: validation

Validate before calling

import os
def readable_file(p):
    return os.path.isfile(p) and os.access(p, os.R_OK)
if not readable_file(filename):
    raise FileNotFoundError(filename)

Try / catch

from pygments.util import ClassNotFound
from pygments.lexers import TextLexer
try:
    lex = load_lexer_from_file(fn)
except ClassNotFound as e:
    if 'cannot read' in str(e):
        lex = TextLexer()
    else:
        raise

Prevention

When it happens

Trigger: load_lexer_from_file('missing.py'), passing a directory, or running from a different cwd so a relative path doesn't resolve.

Common situations: Wrong cwd; path typo; permission denied; file present in dev env but absent in deployed env.

Related errors


AI-assisted analysis of pypa/pip@d7d0d0a394 (2026-08-04). Data as JSON: /data/errors/5c47650158d733b1.json. Report an issue: GitHub.