Is there some way to get during debugging with pdb:
- currently opened python file
- currently active line of code
- indent on the current line of code
and open the file in default text editor?
Example. After running the code below and then using s to step into Path execution and using some command/code I'm looking for I wanted to open file c:\python311\lib\pathlib.py at line 868 and at 5th symbol.
from pathlib import Path
import pdb; pdb.set_trace()
p = Path()
The problem is only about getting current python file in pdb context. Opening file itself is trivial os.system(r"C:\test.py"). Active line code and indent is needed so I'd be able to open it in VS Code at exact position: vsc --goto "C:\test.py:1:5" (comes from vsc --goto "<filepath>:<linenumber>:<x-coordinates>").
It would be nice if it was some native way to do it directly from pdb but since there's nothing related in the documentation, the solution is probably to make some custom method - which is okay too.
I've already tried to use inspect module but it seems that pdb is starting new frame where actual debugged python file is not accessible:
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe())
print(frameinfo.filename, frameinfo.lineno)
# <stdin> 1
I've found a solution. Investigating
pdbmodule, I've found thatPdbclass instance hasself.curframeandself.botframeattributes allowing to access code frames and their paths. When we doimport pdb; pdb.set_trace()it automatically creates an instance ofPdbclass, we need to access.But I haven't found any other way to get the instance besides the hacky one -
pdb.set_trace()is setting system trace (usingsys.settrace) toPdb_instance.trace_dispatch. Therefore we can retrievePdb_instance.trace_dispatchusingsys.gettrace()and getPdbinstance with__self__.Final solution is the
vscode()method in the snippet below. To make it always accessible with pdb you can put it in yourpdb.pyfile (typically it's inPython311\Lib\pdb.py). I guess, the good place for it would be afterdef set_trace(*, header=None):.Then you'd be able to call
import pdb; pdb.vscode()during pdb debugging and it will automatically open current file in VS Code. Voila!You can also add
monkey_patch_vscodeto your pdb - it will patch one of thePdbmethods and you'd be able to open VS Code with justvscode().PS Need to make sure you have
vsc(link to VS Code) is accessable from your system Path.