Skip to content

Provide public API to attach debugger in excepthook and see unhandled exception #723

@Timmmm

Description

@Timmmm

Hi,

I'm trying to set up debugpy to listen() and wait_for_client() when an exception is thrown. Unfortunately I have to do it like this because I'm looking for one exception from a janky hodgepodge of embedded Python processes and Makefiles.

With the following code:

import debugpy

print("Waiting for debugpy on port 5678.")
debugpy.listen(5678)
debugpy.wait_for_client()

raise Exception("test")

If I run python3 main.py and then connect to it, it catches the exception (great):

image

But I can't figure out how to wait for the client on demand when an exception is thrown. Here is my attempt:

import sys
from types import TracebackType
from typing import Any, Callable, Type

def make_debugpy_excepthook() -> Callable[[Type[BaseException], BaseException, TracebackType], Any]:
    """
    Return an excepthook that will initialise debugpy and then call through to
    its exception handler.
    """
    import debugpy

    original_debugpy_excepthook = sys.excepthook

    def debugpy_excepthook(
        type_: Type[BaseException],
        value: BaseException,
        traceback: TracebackType,
    ) -> Any:
        """
        Callback called when an exception is hit and debugpy is enabled.
        """
        if not debugpy.is_client_connected():
            print("Exception thrown. Waiting for debugpy on port 5678.")
            debugpy.listen(5678)
            debugpy.wait_for_client()

        original_debugpy_excepthook(type_, value, traceback)

    return debugpy_excepthook

sys.excepthook = make_debugpy_excepthook()

raise Exception("test")

Unfortunately if I run it it does wait for the debugger, but then it just prints the traceback in the console. I can't figure out how debugpy actually catches exceptions. Does it even use excepthook? Any help appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions