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.
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.
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
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With