For a small module, I want to have a __main__.py
file that is executed via Pythons -m
argument. As per basic docs, this file looks like
import argparse
from . import MyClass
def getparser():
parser = argparse.ArgumentParser()
# […]
return parser
if __name__ == "__main__":
parser = getparser()
args = parser.parse_args()
c = MyClass()
# […]
I want to test this with runpy:
import runpy
def test_main():
runpy.run_module("mymodule")
# […]
which does not work because the __name__
in this case is not __main__
. In principle one could omit the if __name__ == "__main__"
condition to get this working.
But, I also want to document the routine with sphinxarg.ext. This requires to have the getparser()
function available from sphinx. Removing the if __name__ == "__main__"
condition then also runs the module within sphinxdoc, which is not what is wanted.
.. argparse::
:module: mymodule.__main__
:func: getparser
:prog: myprog
How can I structure this so that all use cases work well and the code is well-readable (i.e. the ``getparser()` function and the main code should not be distributed over different files)?