Some times you need to debug python code which is executed by another process and and in this cases rpdb comes in handy.
rpdb is a wrapper around pdb that re-routes stdin and stdout to a socket handler. By default it opens the debugger on port 4444
And then you need run this in terminal to connect to this process.
And you will get pdb promt
The Python Debugger: Step-through Debugging with _pdb_
The Python Standard Library includes an interactive debugging library called pdb. pdb has extensive capabilities, the most commonly used being the ability to 'step-through' a program.
To immediately enter into step-through debugging use:
This will start the debugger at the first line of the program.
Usually you will want to target a specific section of the code for debugging. To do this we import the pdb library and use set_trace() to interrupt the flow of this troubled example code.
Running this program will launch the interactive debugger.
Often this command is used on one line so it can be commented out with a single # character
At the (Pdb) prompt commands can be entered. These commands can be debugger commands or python. To print variables we can use p from the debugger, or python's print.
To see list of all local variables use
These are good debugger commands to know:
The debugger can also evaluate python interactively:
If any of your variable names coincide with the debugger commands, use an exclamation mark '!' before the var to explicitly refer to the variable and not the debugger command. For example, often it might so happen that you use the variable name 'c' for a counter, and you might want to print it while in the debugger. a simple 'c' command would continue execution till the next breakpoint. Instead use '!c' to print the value of the variable as follows:
Via IPython and ipdb
If IPython (or Jupyter) are installed, the debugger can be invoked using:
When reached, the code will exit and print:
Clearly, this means that one has to edit the code. There is a simpler way:
This will cause the debugger to be called if there is an uncaught exception raised.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0