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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With