views:

51

answers:

2

Is there a convenient way to get a more detailed stack trace on a Python exception? I'm hoping to find a wrapper utility/module or some other way to get a bit more info from the stack trace without having to actually modify the Python script that generates it. I'd like to be able to use this when running unit tests, or doctests, or when running utilities or inline scripts from the shell.

Specifically I think I'd like to have the values of local variables, or maybe just the values of the arguments passed to the innermost function in the stack trace. Some options to set the detail level would be nifty.

+1  A: 

Not specifically related to your problem, but you might find this code useful -- automatically starts up the python debugger when a fatal exception occurs. Good for working with interactive code. It's originally from ActiveState

# 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
synthesizerpatel
Hey, thanks for that. I ended up wrapping your code in a [module](http://pypi.python.org/pypi/coroner) to make it convenient to invoke pdb debugging with `python -m coroner some_script.py`. Umm, hope that's okay? I gave you attribution in the docs. I will probably change the module later to spit out stack traces like I want them so I don't have to dig them out with pdb, and so I can use it for unit tests and such. In the meantime, though, this might be useful to somebody.
intuited
Hey, you can do this with `ipython` too, I just realized. You pass the `-pdb` option before passing `-c ...` or a filename. It doesn't seem to support `-m ...` but maybe it could be made to do that by passing `/usr/lib/python../runpy.py` as the filename.
intuited