views:

23

answers:

3

Besides wrapping all your code in try except, is there any way of achieving the same thing as running your script like python -mpdb script? I'd like to be able to see what went wrong when an exception gets raised.

A: 

import pdb; pdb.set_trace()

Source: http://docs.python.org/library/pdb.html

kwatford
Yeah, but this will stop at the line with `pdb.set_trace`. I want it to automatically stop when an exception gets raised.
Geo
You could try using pdb.post_mortem (also in that doc). Pass it the exception's traceback. You'll have to catch it somewhere to do this, of course.
kwatford
+2  A: 

If you do not want to modify the source then yOu could run it from ipython - an enhanced interactive python shell.

e.g. run ipython then execute %pdb on to enable post-mortem debugging. %run scriptname will then run the script and automatically enter the debugger on any uncaught exceptions.

Alternatively %run -d scriptname will start the script in the debugger.

Dave Kirby
A: 
python -i script

will leave you in the interactive shell when an exception gets raised; then

import pdb
pdb.pm()

will put you into the post-mortem debugger so you can do all the usual debugging things.

This should work as long as your script does not call sys.exit. (Which scripts should never do, because it breaks this very useful technique! as well as making them harder to write tests for.)

Vicki Laidler