Skip to content

An exception occurred: AttributeError module 'sys' has no attribute 'real_prefix' #923

Closed

Description

@sunpub

File "C:\Users\XXX.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy\common\util.py", line 1, in
# Copyright (c) Microsoft Corporation. All rights reserved.
^^^^^^^^^^^^^^^
File "C:\Users\XXX.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy\common\util.py", line 16, in evaluate
return eval(expr, {}, sys.modules)
File "C:\Users\XXX.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy\common\log.py", line 297, in
get_paths = lambda: util.evaluate(expr)
File "C:\Users\XXX.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy\common\log.py", line 299, in report_paths
paths = get_paths()
File "C:\Users\XXX.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy\common\log.py", line 328, in get_environment_description
report_paths("sys.real_prefix")
File "C:\Users\XXX.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy\common\log.py", line 372, in describe_environment
info("{0}", get_environment_description(header))
File "C:\Users\XXX.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy\server\api.py", line 56, in ensure_logging
log.describe_environment("Initial environment:")
File "C:\Users\XXX.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy\server\cli.py", line 492, in main
api.ensure_logging()
File "C:\Users\XXX.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy_main_.py", line 71, in
cli.main()
AttributeError: module 'sys' has no attribute 'real_prefix'

Activity

  1. rchiodo commented on Jan 9, 2026

    @rchiodo
    Contributor

    Something is changing 'eval' to not work. This code works fine for me. You can try sticking this in the file you're debugging and see what happens:

    import os
    import sys
    import inspect
    
    def force_str(s, encoding, errors="strict"):
        """Converts s to str, using the provided encoding. If s is already str,
        it is returned as is.
        """
        return s.decode(encoding, errors) if isinstance(s, bytes) else str(s)
    
    def nameof(obj, quote=False):
        """Returns the most descriptive name of a Python module, class, or function,
        as a Unicode string
    
        If quote=True, name is quoted with repr().
    
        Best-effort, but guaranteed to not fail - always returns something.
        """
    
        try:
            name = obj.__qualname__
        except Exception:
            try:
                name = obj.__name__
            except Exception:
                # Fall back to raw repr(), and skip quoting.
                try:
                    name = repr(obj)
                except Exception:
                    return "<unknown>"
                else:
                    quote = False
    
        if quote:
            try:
                name = repr(name)
            except Exception:
                pass
    
        return force_str(name, "utf-8", "replace")
    
    def srcnameof(obj):
        """Returns the most descriptive name of a Python module, class, or function,
        including source information (filename and linenumber), if available.
    
        Best-effort, but guaranteed to not fail - always returns something.
        """
    
        name = nameof(obj, quote=True)
    
        # Get the source information if possible.
        try:
            src_file = inspect.getsourcefile(obj)
        except Exception:
            pass
        else:
            name += f" (file {src_file!r}"
            try:
                _, src_lineno = inspect.getsourcelines(obj)
            except Exception:
                pass
            else:
                name += f", line {src_lineno}"
            name += ")"
    
        return name
    
    def evaluate(code, path=__file__, mode="eval"):
        # Setting file path here to avoid breaking here if users have set
        # "break on exception raised" setting. This code can potentially run
        # in user process and is indistinguishable if the path is not set.
        # We use the path internally to skip exception inside the debugger.
        expr = compile(code, path, "eval")
        return eval(expr, {}, sys.modules)
    
    def swallow_exception(msg, *args, level="error", **kwargs):
        print(msg.format(*args, **kwargs))
    
    def get_environment_description(header):
        import sysconfig
        import site  # noqa
    
        result = [header, "\n\n"]
    
        def report(s, *args, **kwargs):
            result.append(s.format(*args, **kwargs))
    
        def report_paths(get_paths, label=None):
            prefix = f"    {label or get_paths}: "
    
            expr = None
            if not callable(get_paths):
                expr = get_paths
                get_paths = lambda: evaluate(expr)
            try:
                paths = get_paths()
            except AttributeError:
                report("{0}<missing>\n", prefix)
                return
            except Exception:  # pragma: no cover
                swallow_exception(
                    "Error evaluating {0}",
                    repr(expr) if expr else srcnameof(get_paths),
                    level="info",
                )
                return
    
            if not isinstance(paths, (list, tuple)):
                paths = [paths]
    
            for p in sorted(paths):
                report("{0}{1}", prefix, p)
                if p is not None:
                    rp = os.path.realpath(p)
                    if p != rp:
                        report("({0})", rp)
                report("\n")
    
                prefix = " " * len(prefix)
    
        report("System paths:\n")
        report_paths("sys.executable")
        report_paths("sys.prefix")
        report_paths("sys.base_prefix")
        report_paths("sys.real_prefix")
        report_paths("site.getsitepackages()")
        report_paths("site.getusersitepackages()")
    
        site_packages = [
            p
            for p in sys.path
            if os.path.exists(p) and os.path.basename(p) == "site-packages"
        ]
        report_paths(lambda: site_packages, "sys.path (site-packages)")
    
        for name in sysconfig.get_path_names():
            expr = "sysconfig.get_path({0!r})".format(name)
            report_paths(expr)
    
        report_paths("os.__file__")
        report_paths("threading.__file__")
        report_paths("debugpy.__file__")
        report("\n")
    
        importlib_metadata = None
        try:
            import importlib_metadata
        except ImportError:  # pragma: no cover
            try:
                from importlib import metadata as importlib_metadata
            except ImportError:
                pass
        if importlib_metadata is None:  # pragma: no cover
            report("Cannot enumerate installed packages - missing importlib_metadata.")
        else:
            report("Installed packages:\n")
            try:
                for pkg in importlib_metadata.distributions():
                    report("    {0}=={1}\n", pkg.name, pkg.version)
            except Exception:  # pragma: no cover
                swallow_exception(
                    "Error while enumerating installed packages.", level="info"
                )
    
        return "".join(result).rstrip("\n")
    
    print(get_environment_description("Environment description:"))

    That code is identical to what debugpy is running and I get no such exception. The eval is failing for you for some reason.

  2. Charron-Lin commented on Jan 15, 2026

    @Charron-Lin

    I installed Python 3.10.11, and debugging also reports this error. It started recently.
    Have you solved this problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    triage-neededNeeds assignment to the proper sub-team

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions