I need to set a breakpoint in a file other than the current file, but I don't want to quit out of pdb and go into my editor to find out what line number it should be on.
How do I list lines of source code in a file that is not the currently open file?
Listing Source Code To see a shorter snippet of code, use the command l (list). Without arguments, it will print 11 lines around the current line or continue the previous listing.
Starting Python Debugger To start debugging within the program just insert import pdb, pdb. set_trace() commands. Run your script normally, and execution will stop where we have introduced a breakpoint. So basically we are hard coding a breakpoint on a line below where we call set_trace().
There are many different ways to use pdb, but the simplest is by using its pdb. set_trace() function. Wherever you put this line in your code, the Python interpreter will stop and present an interactive debugger command prompt.
The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame.
I don't think it's possible using only pdb, but it's also easy to get it to work following simple steps:
rich
to highlight your code (take a look at https://pypi.org/project/rich/)inspect
to get source of any module, class, method, function, traceback, frame, or code object that you can import (check https://docs.python.org/3/library/inspect.html#retrieving-source-code)Example:
from inspect import getsourcelines
from rich import print
from some_py_file import something
if __name__ == '__main__':
src = ''.join(getsourcelines(something)[0])
print(src)
Above code is done in a python script, but you can do it inside a pdb session. It will print syntax highlighted and indented code.
Output:
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