Put this at the top of your __main__.py
:
#!/usr/bin/env python3
# Declare itself as package if needed
if __name__ == '__main__' and __package__ is None:
import os, sys, importlib
parent_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.dirname(parent_dir))
__package__ = os.path.basename(parent_dir)
importlib.import_module(__package__)
# Continue with your code
do_things()
This way, these 2 commands become equivalent:
cd /parent/folder; python -m module_folder
python /parent/folder/module_folder/__main__.py
Just use the 2nd syntax for debugging:
pudb /parent/folder/module_folder/__main__.py
or
python3 -m pdb /parent/folder/module_folder/__main__.py
The same works for Python 2.
You can safely remove from the above code the part __name__ == '__main__' and
because, as you are writing in __main__.py
, it would always be True
. However, it's a common practice to put it. See PEP 366 and this other answer.