Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch Python debugger while simultaneously executing module as script

Tags:

python

pdb

When developing a Python package, it's very convenient to use the -m option to run modules inside the package as scripts for quick testing. For example, for somepackage with module somemodule.py inside it, invoking

python -m somepackage.somemodule

from the directory where somepackage resides will run somemodule.py as though the submodule were __main__. Using this calling syntax is especially important if the package is using explicit relative imports as described here.

Similarly, it is also convenient to use the -m option to debug a script, as in

python -m pdb somescript.py

Is there any way to do both at the same time? That is, can I call a module as though it were a script and simultaneously launch into the debugger? I realize I can go into the code itself and insert import pdb; pdb.set_trace() where I want to break, but I'm trying to avoid that.

like image 801
Jed Avatar asked Aug 10 '13 21:08

Jed


2 Answers

Building on @jed's answer, I built this module:

import pdb
import runpy
import sys


def main():
    module = sys.argv[1]
    sys.argv[1:] = sys.argv[2:]
    pdb.runcall(runpy.run_module, module, run_name='__main__')


__name__ == '__main__' and main()

Put that module as mpdb.py anywhere in your Python Path (current directory works), then you may invoke:

python -m mpdb somepackage.somemodule even with args
like image 139
Jason R. Coombs Avatar answered Oct 14 '22 09:10

Jason R. Coombs


After experimenting with this for quite some time, it turns out that this approach actually works:

python -c "import runpy; import pdb; pdb.runcall(runpy.run_module, 'somepackage.somemodule', run_name='__main__')"

For some reason, the use of pdb.runcall over pdb.run is important.

like image 22
Jed Avatar answered Oct 14 '22 10:10

Jed