Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breakpoint-induced interactive debugging of Python with IPython

Say I have an IPython session, from which I call some script:

> run my_script.py

Is there a way to induce a breakpoint in my_script.py from which I can inspect my workspace from IPython?

I remember reading that in previous versions of IPython one could do:

from IPython.Debugger import Tracer;     

def my_function():
    x = 5
    Tracer()
    print 5;

but the submodule Debugger does not seem to be available anymore.

Assuming that I have an IPython session open already: how can I stop my program a location of my choice and inspect my workspace with IPython?

In general, I would prefer solutions that do not require me to pre-specify line numbers, since I would like to possibly have more than one such call to Tracer() above and not have to keep track of the line numbers where they are.

like image 307
Amelio Vazquez-Reina Avatar asked Jan 31 '13 21:01

Amelio Vazquez-Reina


People also ask

How do I debug with IPython?

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.


4 Answers

The Tracer() still exists in ipython in a different module. You can do the following:

from IPython.core.debugger import Tracer  def my_function():     x = 5     Tracer()()     print 5 

Note the additional call parentheses around Tracer

edit: For IPython 6 onwards Tracer is deprecated so you should use set_trace() instead:

from IPython.core.debugger import set_trace  def my_function():     x = 5     set_trace()     print 5 
like image 96
pankaj Avatar answered Oct 19 '22 00:10

pankaj


You can run it and set a breakpoint at a given line with:

run -d -b12 myscript 

Where -b12 sets a breakpoint at line 12. When you enter this line, you'll immediately drop into pdb, and you'll need to enter c to execute up to that breakpoint.

like image 21
Wilduck Avatar answered Oct 19 '22 00:10

Wilduck


This is the version using the set_trace() method instead of the deprecated Tracer() one.

from IPython.core.debugger import Pdb

def my_function():
    x = 5
    Pdb().set_trace()
    print 5
like image 44
Medhat Omr Avatar answered Oct 18 '22 23:10

Medhat Omr


Inside the IPython shell, you can do

from IPython.core.debugger import Pdb
pdb = Pdb()
pdb.runcall(my_function)

for example, or do the normal pdb.set_trace() inside your function.

like image 24
Daniel Roseman Avatar answered Oct 18 '22 22:10

Daniel Roseman