简体   繁体   中英

How to debug python code running inside exec()

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

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 """ """.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM