From Newsgroup: comp.lang.python
So, ipdb is the ipython version of pdb. In fact, post_mortem is a
pdb function. I use ipdb because its REPL is a bit nicer to work
with then pdb.
-----Original Message-----
From: Stefan Ram <
ram@zedat.fu-berlin.de>
Subject: Re: Drop into REPL when your program crashes.
Date: 09/08/2025 06:04:16 PM
Newsgroups: comp.lang.python
Annada Behera <
annada@tilde.green> wrote or quoted:
Recently I have been increasingly adding this piece of code as
a preamble to a lot of my code.
-a-a import (sys, os, ipdb)
-a-a def debug_hook(exc_type, exc_value, traceback):
-a-a-a-a-a-a if exc_type is KeyboardInterrupt:
-a-a-a-a-a-a-a-a-a-a sys.__excepthook__(exc_type, exc_value, traceback) -a-a-a-a-a-a-a-a-a-a return
-a-a-a-a-a-a print(f"Uncaught exception: {exc_type.__name__}: {exc_value}") -a-a-a-a-a-a ipdb.post_mortem(traceback)
-a-a if os.environ.get('DEBUG'): sys.excepthook = debug_hook
-a Thanks!
-a 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):
-a-a-a i = 2
-a-a-a if issubclass(exc_type, KeyboardInterrupt):
-a-a-a-a-a-a-a # Call the default excepthook for KeyboardInterrupt to allow clean exit
-a-a-a-a-a-a-a sys.__excepthook__(exc_type, exc_value, tb)
-a-a-a-a-a-a-a return
-a-a-a print(f"Uncaught exception: {exc_type.__name__}: {exc_value}")
-a-a-a pdb.post_mortem(tb)
def cause_exception():
-a-a-a # Function to demonstrate an unhandled exception
-a-a-a i = 3
-a-a-a return 1 / 0-a # Will raise ZeroDivisionError
def f():
-a-a-a # Function to demonstrate an unhandled exception
-a-a-a i = 4
-a-a-a cause_exception()
-a-a-a return i
if __name__ == "__main__": # demo code
-a-a-a import os; os.environ['DEBUG'] = 'true'
-a-a-a if os.environ.get('DEBUG'):
-a-a-a-a-a-a-a sys.excepthook = debug_exception_hook
-a-a-a-a-a-a-a print("Debug mode enabled: Using pdb post-mortem on uncaught exceptions.")
-a-a-a else:
-a-a-a-a-a-a-a print("Debug mode not enabled: Regular exception handling.") -a-a-a
-a-a-a # Run demo to trigger exception
-a-a-a i = 5
-a-a-a f()
-a 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-a # Will raise ZeroDivisionError
(Pdb) i
3
(Pdb)
-a .
--- Synchronet 3.21a-Linux NewsLink 1.2