When Python runs a script and an uncatched exception is raised, a traceback is printed and the script is terminated. Python2.1 has introduced sys.excepthook, which can be used to override the handling of uncaught exceptions. This allows to automatically start the debugger on an unexpected exception, even if python is not running in interactive mode.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# code snippet, to be included in 'sitecustomize.py' import sys def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(type, value, tb) else: import traceback, pdb # we are NOT in interactive mode, print the exception... traceback.print_exception(type, value, tb) print # ...then start the debugger in post-mortem mode. pdb.pm() sys.excepthook = info
The above code should be included in 'sitecustomize.py', which is automatically imported by python. The debugger is only started when python is run in non-interactive mode.
If you have not yet a 'sizecustomize.py' file, create one and place it somewhere on your pythonpath.