What changes when you run Python with -m?
python -m package.module finds a module through Python’s import machinery and runs it as the program’s main module. python package/module.py opens that file directly. Only the first form establishes the package context needed for relative imports.
Use -m for modules inside importable packages; run standalone scripts by file path.
Compare what Python sets up
For an ordinary interpreter invocation without path-isolation flags:
| Detail | python package/app.py |
python -m package.app |
|---|---|---|
| Finds code using | The file path | The dotted import name |
__name__ while running |
"__main__" |
"__main__" |
| Package context | None for the directly executed file | package |
__spec__ |
None |
The located module’s specification |
| First search-path location | The script’s directory | The current working directory |
Both forms run the if __name__ == "__main__": block. Finding a submodule also imports its parent package, so its __init__.py can run first.
Watch a relative import use its package context
Create this layout in a scratch directory outside any existing Python project, with an empty sample/__init__.py:
sample/
__init__.py
helpers.py
app.pydef greeting():
return "Hello from the package"from .helpers import greeting
print(__name__)
print(__spec__.parent)
print(greeting())With uv installed, run from the directory containing sample/:
$ uv run python -m sample.app
__main__
sample
Hello from the package
Inside a project, uv run uses its virtual environment and ensures dependencies are installed. This scratch example needs neither project configuration nor third-party dependencies. Pass -m a dotted name: sample.app, not sample/app.py.
Running uv run python sample/app.py instead fails on the relative import with ImportError: attempted relative import with no known parent package. The dot in .helpers means “inside my package,” but direct file execution supplies no package context. Follow the relative-import troubleshooting guide to fix an existing project.
Give a package its own main module
python -m sample executes sample/__main__.py. Add this file:
from .helpers import greeting
print(greeting())$ uv run python -m sample
Hello from the package
Without __main__.py, package execution fails. Ordinary import sample loads __init__.py, not __main__.py.
Keep the package importable
-m does not install packages. Run this example from its parent directory. For a packaged project, especially a src/ layout, install the project into the selected environment.
For No module named ..., follow the ModuleNotFoundError checklist. For a command intended for users, a [project.scripts] entry point gives the installed program a stable command name without exposing its internal module path.