|
|
 |
|
Title: Automatically start the debugger on an exception
Submitter: Thomas Heller
(other recipes)
Last Updated: 2001/07/13
Version no: 1.4
Category:
Debugging
|
|
11 vote(s)
|
|
|
|
Description:
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.
Source: Text Source
import sys
def info(type, value, tb):
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
sys.__excepthook__(type, value, tb)
else:
import traceback, pdb
traceback.print_exception(type, value, tb)
print
pdb.pm()
sys.excepthook = info
Discussion:
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.
|
|
Add comment
|
|
Number of comments: 5
Gui debugger?, Matt Feifarek, 2001/07/18
This is a great idea; I'd love to use it under the PythonWin gui debugger. Any way to make that happen?
I'm using Python as the Active Script language for IIS/ASP, and would love to throw the errors into the PythonWin debugger.
Thanks!
Add comment
using pywin debugger, Christopher Prinos,Christopher Prinos,Christopher Prinos, 2002/07/02
instead of:
import pdb
pdb.pm()
use:
import pywin.debugger
pywin.debugger.pm()
Add comment
Some small improvements, Syver Enstad, 2002/08/20
It is nice to check if the exception is a syntax error
because SyntaxError's can't be debugged.
if hasattr(sys, 'ps1') or not sys.stderr.isatty() or \
type == SyntaxError: # there is nothing to be done on syntax errors
Also nice is just assigning the debug exception hook when the program is run is debug mode.
if __debug__:
sys.excepthook = info
Add comment
Should check if stdin.isatty also, Adam Hupp,Adam Hupp, 2002/11/23
If stdin isn't a tty (e.g. a pipe) and this gets called the pdb code will just start printing it's prompt continually instead of giving a useful traceback. Changing the test to "not (sys.stderr.isatty() and sys.stdin.isatty())" fixes it.
-Adam
Add comment
Addidtional check: sys.stdout.isatty(), Jens Liebehenschel, 2005/10/07
If the standart output is redirected to a file, then you might not want to start the debugger, because you do not see the debugger's output. Under consideration of the previous comments the condition has to be changed to:
if hasattr(sys, 'ps1') or not sys.stderr.isatty() or not sys.stdin.isatty() or not sys.stdout.isatty() or type==SyntaxError:
Add comment
|
|
|
|
|
 |
|