Re: Drop into REPL when your program crashes.

[email protected] (Stefan Ram) 8 Sep 2025 12:34:16 GMT
Newsgroups comp.lang.python
Organization Stefan Ram
Message-ID <[email protected]>
Annada Behera <[email protected]> wrote or quoted:
>Recently I have been increasingly adding this piece of code as
>a preamble to a lot of my code.
>
>    import (sys, os, ipdb)
>
>    def debug_hook(exc_type, exc_value, traceback):
>        if exc_type is KeyboardInterrupt:
>            sys.__excepthook__(exc_type, exc_value, traceback)
>            return
>        print(f"Uncaught exception: {exc_type.__name__}: {exc_value}")
>        ipdb.post_mortem(traceback)
>
>    if os.environ.get('DEBUG'): sys.excepthook = debug_hook

  Thanks! 

  I have changed it a bit to work without "ipdb" and added demo code.

import sys
import os
import pdb

i = 1

def debug_exception_hook(exc_type, exc_value, tb):
    i = 2
    if issubclass(exc_type, KeyboardInterrupt):
        # Call the default excepthook for KeyboardInterrupt to allow clean exit
        sys.__excepthook__(exc_type, exc_value, tb)
        return
    print(f"Uncaught exception: {exc_type.__name__}: {exc_value}")
    pdb.post_mortem(tb)

def cause_exception():
    # Function to demonstrate an unhandled exception
    i = 3
    return 1 / 0  # Will raise ZeroDivisionError

def f():
    # Function to demonstrate an unhandled exception
    i = 4
    cause_exception()
    return i

if __name__ == "__main__": # demo code
    import os; os.environ['DEBUG'] = 'true'

    if os.environ.get('DEBUG'):
        sys.excepthook = debug_exception_hook
        print("Debug mode enabled: Using pdb post-mortem on uncaught exceptions.")
    else:
        print("Debug mode not enabled: Regular exception handling.")
    
    # Run demo to trigger exception
    i = 5
    f()

  Then, I got this dialog:

Debug mode enabled: Using pdb post-mortem on uncaught exceptions.
Uncaught exception: ZeroDivisionError: division by zero
> debug_hook.py(19)cause_exception()
-> return 1 / 0  # Will raise ZeroDivisionError
(Pdb) i
3
(Pdb) 

  .