2

Is there a way to invoke a python program such that it will run normally if it does not die, but if it has an uncaught exception, to behave as though it were run with -i?

The reason is that I am running my python program from an external script, and it does not encounter the exceptional condition until several runs in. So I want to just lazily go into interactive mode so I can then load up the debug module and look at the postmortem to see the stack variables, but not to have it fall into the interactive prompt for all the earlier runs of the program which do succeed.

Steven Lu
  • 41,389
  • 58
  • 210
  • 364
  • 2
    related: [Starting python debugger automatically on error](http://stackoverflow.com/q/242485/4279) – jfs Jun 11 '13 at 00:55

1 Answers1

4

Stuff a function into sys.excepthook that creates a console using code.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Oh wow it's gonna be hard to google for a module named `code`. Edit: Brilliant! – Steven Lu Jun 11 '13 at 00:49
  • Oh this is excellent. I was actually hunting for a way to inject an interactive prompt prior to dying on an exception all yesterday! I was gonna settle for the postmortem (which is plenty helpful as it is, with a stack var snapshot!) – Steven Lu Jun 11 '13 at 00:51
  • Hey, is there a way to squeeze `pdb` to run on an exception with excepthook or some such? – Steven Lu Jun 11 '13 at 03:04
  • @StevenLu, just run `python -m pdb buggycode.py` to enter the debugger on an uncaught exception. Note that you need to press `c` once at the beginning to start execution. – Will Jul 17 '14 at 22:01