dropping into the debugger on an exception
Thomas Heller
theller at python.net
Wed Jun 9 03:13:00 EDT 2004
Jon Perez <jbperez808 at yahoo.com> writes:
> (sorry for the duplicate post, just wanted to make the subject
> line clearer)
>
> How do you set up pdb such that you will automatically
> get dropped into its prompt if an unanticipated exception
> occurs in a script you are using?
>
> ASPN Python cookbook gives you the following method
> which you can add to your script and hook into sys.excepthook.
> But is there a way to do it without adding stuff to your
> script? (It's okay if this means having to invoke the script
> from within pdb, but #1, I don't know how to get it stay inside
> pdb in the case of an /unanticipated/ exception. And #2, I
> don't know how to pass [the equivalent of] command-line
> arguments to a script invoked from within pdb.)
[...]
Is the description in the cookbook unclear? You do *not* have to add
anything to your script - save the code as a file
C:\Python23\sitecustomize.py and everything will work. And you don't
have to start the script from within pdb. The sitecustomize module is
automatically imported when Python starts - if it is found.
I'm appending the version I currently use, maybe it has some
improvements not mentioned in the online version.
Thomas
"""
# code snippet, to be included in 'sitecustomize.py'
import sys
import traceback, pdb
##import pywin.debugger
def info(type, value, tb,
excepthook=sys.__excepthook__,
print_exc=traceback.print_exception,
## debug=pywin.debugger.pm):
debug=pdb.pm):
if not __debug__ \
or not sys \
or hasattr(sys, 'ps1') \
or not sys.stderr.isatty() \
or not sys.stdin.isatty() \
or not hasattr(sys, "last_traceback"):
# call the default hook if one of the following conditions
# is satisfied:
# - Python is running with the -O flag (__debug__ == 0)
# - sys is None (python is shutting down, and the sys module
# already has been cleared)
# - we are in interactive mode (sys has a 'ps1' attribute)
# - sys.stderr is not a tty: we are not connected to a terminal
# - no last_traceback attribute in sys (SyntaxError)
excepthook(type, value, tb)
else:
# print the exception...
print_exc(type, value, tb)
# ...then start the debugger in post-mortem mode.
debug()
sys.excepthook = info
"""
More information about the Python-list
mailing list