-
Notifications
You must be signed in to change notification settings - Fork 288
Debugging with pdb
To use pdb you will need to run Pootle in the foreground:
pootle runserver
You can also use pdb in tests or commands, or any other code that runs from the console.
You can add a breakpoint anywhere in Python code
def some_function():
do_something()
import pdb; pdb.set_trace()
do_something_else()
When this code is run the python interpreter will stop whenever it reaches this line of code, and allow you to interact with the program from the console where Pootle is being run.
If you are expecting the code to be triggered from a view, open the corresponding web page, and then switch back to your console.
-
l
: list the lines of code surrounding the breakpoint (you can use egl 20
to view lines around line 20) -
n
: execute the next line of code (or "step over") -
c
: continue program execution -
s
: "step into" the next line of code -
q
: quit the breakpoint
in most cases ctrl-c
will execute the program altogether
You can find what code called a particularly method or function using inspect
When doing this inside pdb - you need to move up the stack beyond the pdb code
import inspect
inspect.stack()[10]
Adding pdb inside a loop can cause the program to break repeatedly, often not when you actually wanted it to do so.
You can place the break before the loop, if you don't need to inspect variables inside it.
Alternatively add a condition to ensure that pdb is only activated at the point you need to introspect.
Often you break at a certain point in the code and then realise you need to introspect at some point later in the program execution, but don't want to have to step over/into the code in between.
In this case you can set a further break point with eg b 23
where a breakpoint would be added at line 23. You can then use c
to continue program execution, and you should reach your new breakpoint
pdb causes program execution to halt - this is not what you want in production!
Add commit hooks to prevent pdb being added and/or lint code to ensure it cannot ever reach production.