Breakpoint-induced interactive debugging of Python

2019-01-31 12:09发布

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.

5条回答
我命由我不由天
2楼-- · 2019-01-31 12:38

I have always had the same question and the best workaround I have found which is pretty hackey is to add a line that will break my code, like so:

...
a = 1+2
STOP
...

Then when I run that code it will break, and I can do %debug to go there and inspect. You can also turn on %pdb to always go to point where your code breaks but this can be bothersome if you don't want to inspect everywhere and everytime your code breaks. I would love a more elegant solution.

查看更多
一夜七次
3楼-- · 2019-01-31 12:40

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
查看更多
Lonely孤独者°
4楼-- · 2019-01-31 12:41

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.

查看更多
Juvenile、少年°
5楼-- · 2019-01-31 12:42

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
查看更多
Anthone
6楼-- · 2019-01-31 12:48

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.

查看更多
登录 后发表回答