Lincoln Bergeson
Lincoln Bergeson

Reputation: 3451

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?

Upvotes: 8

Views: 2801

Answers (1)

Kafka4PresidentNow
Kafka4PresidentNow

Reputation: 396

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

Upvotes: 1

Related Questions