Python run module with and without "-m" option and import path setting
## if there is a "__main__.py" file in a folder, you can use the bellow command to run the "__main__.py" file:
python .
# or
python __main__.py
# but NOT
python -m .
# which won't work.
## it is recommended to use "-m" option to run a module in a package, e.g.
python -m pkga.pkgb.mymodule
# In this way, package semantics (including relative imports) are honoured
# relative imports looks like:
from . import modmule1, module2 # will look from the same folder as the module which is importing module1
from .module3 import func1
from ..module4 import func2
# the below import:
from moduleA import funcA
# will search current folder, then from sys.path
# assume the directory structure:
root/pkga/pkgb/mymodule.py
# the work directory is in "root". there are two ways to run mymodule.py from "root" directory:
# run the module with -m option:
python -m pkga.pkgb.mymodule
# here, package semantics (including relative imports) are honoured,
# the work directory ("root") is added to sys.path, import pattern "from pkga.pkgb import mymudule" will work.
# and the package directory (root/pkga/pkgb) itself is never added to the system path,
# without -m option:
python pkga/pkgb/mymodule.py
# the "package" directory is first added to the path (i.e. sys.path),
#and then the files are run normally, without package semantics.
# a good reference: the last answer!!
# https://stackoverflow.com/questions/4042905/what-is-main-py#:~:text=A%20module's%20__name__,or%20from%20an%20interactive%20prompt.&text=For%20a%20package%2C%20the%20same,module%20is%20run%20with%20%2Dm%20.