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.


Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source