开发者

python: run interactive python shell from program

开发者 https://www.devze.com 2023-04-11 10:42 出处:网络
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

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 r开发者_StackOverflow社区ecreate 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?


import code

code.interact(local=locals())

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

import pdb

pdb.set_trace()


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


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.


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) 


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

0

精彩评论

暂无评论...
验证码 换一张
取 消