tags:

views:

70

answers:

2

Suppose I have a script that does a lot of stuff, and doesn't work well somewhere near the end. I'd love to be able to add a start_ipython() function at that point, which would stop the script at this point, and let me inspect variables and so on with ipython. How can I do this?

+3  A: 

Easiest way is to use the built-in debugger. At the point you want execution to stop, just do:

import pdb; pdb.set_trace()

and you'll be dumped into the pdb shell, which allows you to inspect variables and change them.

There is also an external ipdb package which you can get via easy_install which should work the same way.

Daniel Roseman
Thanks! Any way to use ipython instead of the pdb shell, though?
static_rtti
Yes, see my edit above.
Daniel Roseman
Nice, thank you again!
static_rtti
+7  A: 

In the region where you want to drop into ipython, define this

def start_ipython():
   from IPython.Shell import IPShellEmbed
   shell = IPShellEmbed()
   shell()

and call start_ipython where you want to drop into the interpreter.

This will drop you into an interpreter and will preserve the locals() at that point.

If you want a regular shell, do this

def start_python():
   import code
   code.interact()

Check the documentation for the above functions for details. I'd recommend that you try the ipython one and if it throws an ImportError, switch to normal so that it will work even if ipython is not installed.

Noufal Ibrahim
+1 for the last paragraph (try iPython first, code.interact on import error)
digitalarbeiter
Well, that's what the `shell` command for the turbogears framework does and I liked the behaviour. Thanks for your +1.
Noufal Ibrahim