views:

190

answers:

3

If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred.

+10  A: 

You want the code module.

#!/usr/bin/env python

import code    
code.interact("Enter Here")
Douglas Leeder
+2  A: 

Set the PYTHONINSPECT environment variable. This can also be done in the script itself:

import os
os.environ["PYTHONINSPECT"] = "1"

For debugging unexpected exceptions, you could also use this nice recipe http://code.activestate.com/recipes/65287/

theller
+2  A: 

The recipe metioned in the other answer using sys.excepthook, sounds like what you want. Otherwise, you could run code.interact on program exit:

import code
import sys
sys.exitfunc = code.interact
asmundg