Hacker News new | ask | show | jobs
by davmre 4587 days ago
There's a nice trick to enable this behavior for standard Python code run at the command line. Write the body of your code inside a main() function, then call it using the following toplevel block:

  if __name__ == "__main__":
      try:
          main()
      except KeyboardInterrupt: # allow ctrl-C
          raise
      except Exception as e:
          import sys, traceback, pdb
          print e
          type, value, tb = sys.exc_info()
          traceback.print_exc()
          pdb.post_mortem(tb)
This will catch any exceptions and throw you into PDB in the context where the exception was raised. You probably don't want to leave it in production code, but it's super useful for development.
2 comments

You don't need this trickery.

    $ python -m pdb yourscript.py
    (Pdb) c
Will let you inspect the local scope after an uncaught exception.
Yeah, that's probably a better general solution. That said, there are some contexts, e.g. working on academic research code which is always buggy, where you really do want debugger-on-exception to be the default behavior, so that you don't have to remember to type -m pdb every single time you run your code. I guess you could alias python to "python -m pdb", but that's opening a whole new can of worms. :-)
Minor gripe, the except KeyboardInterrupt isn't necessary, since KeyboardInterrupt is a BaseException, not an Exception.
Only since Python 2.5 I believe.