How to debug python code running inside exec()

616 Views Asked by At

I'm trying to debug a plugin code that I'm running inside exec command

is there a way to debug it somehow? for example:

code='''
breakpoint()
foo=5
print(foo)
'''
exec(code)

I want to stop before foo is printed, and do list (pdb) command and see the code

2

There are 2 best solutions below

1
On
In [8]: code='import ipdb\nnfoo=5\nipdb.set_trace()\nprint(nfoo**2)'

In [9]: exec(code)
> <string>(4)<module>()

ipdb> nfoo
5
ipdb> nfoo = 6
ipdb> c
36

After ipdb.set_trace() ipdb will start. You can go to the next break using c or to next line with n. check the following cheetsheet: cheetsheet

code='import ipdb\nnfoo=5\nipdb.set_trace()\nprint(nfoo**2)'

In [13]: exec(code)
None
> <string>(4)<module>()

ipdb> nfoo
5
ipdb> nfoo = 6
ipdb> n
36

Note: it's easier to place your code inside a """ """.

0
On

found it in pudb I can add :

_MODULE_SOURCE_CODE = code

or

linecache.lazycache("<path>/code.py",module_globals= None)

or

linecache.cache[self.path] = (len(code), None, code.splitlines(True), path)

or in VScode I can just add the file to somewhere vscode can find it and just set :

"justMyCode": false, in launch.json file