Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use IPython magic functions in ipdb shell

When debugging Python script using ipdb my_script.py, I want to use IPython magic functions like %paste, %cd in ipdb debug session shell. Is is possible and how?

like image 416
Fish Monitor Avatar asked Apr 24 '13 06:04

Fish Monitor


People also ask

How do I use IPython for debugging?

IPython has another way to start a debugger. You don't need to modify the source code of any file as we did before. If you run the %run -d filename.py magic command, IPython will execute the filename.py file and put a breakpoint on the first line there. It's just as if you would put the import ipdb; ipdb.

What does IPDB mean in Python?

ipdb, the IPython-enabled Python Debugger, is a third party interative debugger with all pdb's functionality and adds IPython support for the interactive shell, like tab completion, color support, magic functions and much more. You use ipdb just as you use pdb but with an enhanced user experience.

What are magic commands in IPython?

The magic commands, or magics, are handy commands built into the IPython kernel that make it easy to perform particular tasks, for example, interacting Python's capabilities with the operating system, another programming language, or a kernel. IPython provides two categories of magics: line magics and cell magics.


2 Answers

According to the ipdb Github repo magic IPython functions are not available. Fortunately, the IPython debugger provides a couple of clues of how to get this functionality without launching a separate IPython shell.

Here is what I did to run %cpaste:

ipdb> from IPython import get_ipython ipdb> shell = get_ipython() ipdb> shell.find_line_magic('cpaste')() Pasting code; enter '--' alone on the line to stop or use Ctrl-D. :for i in range(0,5): :       print i :-- 0 1 2 3 4 

This way, you can step through your code and have access to all the IPython magic functions via the method find_line_magic(your_magic_function).

like image 51
Peter Malmgren Avatar answered Oct 13 '22 22:10

Peter Malmgren


You can open a IPython shell inside a stack, just like pdb does. Do the following:

  • Import embed() from IPython, and put it inside your code.
  • Run the script

Example:

from IPython import embed  def some_func():     i = 0     embed()     return 0 

In Python shell:

>>> te.func()  IPython 1.0.0 -- An enhanced Interactive Python. (...)  In [1]: %whos  Variable   Type    Data/Info i          int     0  In [2]: 

Was that what you were looking for?

like image 32
Lucas Ribeiro Avatar answered Oct 14 '22 00:10

Lucas Ribeiro