Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python PDB, how do I list the source code of a file other than the current file?

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?

like image 985
Lincoln Bergeson Avatar asked Mar 19 '19 21:03

Lincoln Bergeson


People also ask

Which command is used to display the source code for the current file in Python?

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.

How do I use pdb code in Python?

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().

What does pdb Set_trace () do?

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.

What is pdb and list out some functions?

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.


1 Answers

I don't think it's possible using only pdb, but it's also easy to get it to work following simple steps:

  1. Get rich to highlight your code (take a look at https://pypi.org/project/rich/)
  2. Use 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)
  3. print what you want

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:

enter image description here

like image 126
Kfcaio Avatar answered Oct 21 '22 12:10

Kfcaio