Can I put a breakpoint in a running Python program that drops to the interactive terminal?

后端 未结 6 2121
清酒与你
清酒与你 2020-12-24 06:51

I\'m not sure if what I\'m asking is possible at all, but since python is an interpreter it might be. I\'m trying to make changes in an open-source project but because there

6条回答
  •  情书的邮戳
    2020-12-24 07:06

    A one-line partial solution is simply to put 1/0 where you want the breakpoint: this will raise an exception, which will be caught by the debugger. Two advantages of this approach are:

    • Breakpoints set this way are robust against code modification (no dependence on a particular line number);

    • One does not need to import pdb in every program to be debugged; one can instead directly insert "breakpoints" where needed.

    In order to catch the exception automatically, you can simply do python -m pdb prog.py… and then type c(ontinue) in order to start the program. When the 1/0 is reached, the program exits, but variables can be inspected as usual with the pdb debugger (p my_var). Now, this does not allow you to fix things and keep running the program. Instead you can try to fix the bug and run the program again.

    If you want to use the powerful IPython shell, ipython -pdb prog.py… does the same thing, but leads to IPython's better debugger interface. Alternatively, you can do everything from within the IPython shell:

    • In IPython, set up the "debug on exception" mode of IPython (%pdb).
    • Run the program from IPython with %run prog.py…. When an exception occurs, the debugger is automatically activated and you can inspect variables, etc.

    The advantage of this latter approach is that (1) the IPython shell is almost a must; and (2) once it is installed, debugging can easily be done through it (instead of directly through the pdb module). The full documentation is available on the IPython pages.

提交回复
热议问题