drop into the interpreter

Ray Buvel rlbuvel at gmail.com
Fri Aug 13 08:15:06 EDT 2004


Hoang Do wrote:
> is there a facility to inspect the run-time of a python script?
> Essentially, it would execute a script to a set specific point and then drop
> into the interpreter.  Something like a "Stop" or "Break"?

This can be done fairly easily by creating a module (lets call it 
interactive) with the following code in it.
-----------
import sys,os

def debug_exception(type, value, traceback):
     # Restore redirected standard I/O
     sys.stdin = sys.__stdin__
     sys.stdout = sys.__stdout__
     sys.stderr = sys.__stderr__

     # Kick the interpreter into interactive mode and call the original
     # exception handler.
     os.environ['PYTHONINSPECT'] = '1'
     sys.__excepthook__(type, value, traceback)

sys.excepthook = debug_exception
-----------

Now if you import this module and raise an unhandled exception, you will 
be in interactive mode.  In other words, I think the following script 
does what you are asking for.

-----------
import interactive

raise RuntimeError('Interactive Mode')
-----------

This also has the advantage that if there are no unhandled exceptions in 
your script, the script runs and terminates normally.

Enjoy,
Ray Buvel



More information about the Python-list mailing list