python: run interactive python shell from program

Question:

I often have the case that I’ll be writing a script, and I’m up to a part of the script where I want to play around with some of the variables interactively. Getting to that part requires running a large part of the script I’ve already written.

In this case it isn’t trivial to run this program from inside the shell. I would have to recreate the conditions of that function somehow.

What I want to do is call a function, like runshell(), which will run the python shell at that point in the program, keeping all variables in scope, allowing me to poke around in it.

How would I go about doing that?

Asked By: Claudiu

||

Answers:

import code

code.interact(local=locals())

But using the Python debugger is probably more what you want:

import pdb

pdb.set_trace()
Answered By: Michael Hoffman

You can use the python debugger (pdb) set_trace function.

For example, if you invoke a script like this:

def whatever():
    x = 3
    import pdb
    pdb.set_trace()

if __name__ == '__main__':
    whatever()

You get the scope at the point when set_trace is called:

$ python ~/test/test.py
--Return--
> /home/jterrace/test/test.py(52)whatever()->None
-> pdb.set_trace()
(Pdb) x
3
(Pdb) 
Answered By: jterrace

Not exactly a perfect source but I’ve written a few manhole’s before, here is one I wrote for an abandoned pet project http://code.google.com/p/devdave/source/browse/pymethius/trunk/webmud/handlers/konsole.py

And here is one from the Twisted Library http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.1.0/twisted/manhole/telnet.py the console logic is in Shell.doCommand

Answered By: David

For practicality I’d like to add that you can put the debugger trace in a one liner:

import pdb; pdb.set_trace()

Which is a nice line to add to an editor that supports snippets, like TextMate or Vim+SnipMate. I have it set up to expand “break” into the above one liner.

Answered By: Hubro

By far the most convenient method that I have found is:

import IPython
IPython.embed()

You get all your global and local variables and all the creature comforts of IPython: tab completion, auto indenting, etc.

You have to install the IPython module to use it of course:

pip install ipython
Answered By: staticd
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.