Sub topic 11
Running modules and packages with python -m
This chapter assumes you know how imports work, what sys.path is, and how a package with __init__.py is laid out. It builds on the __main__ guard and relative imports covered earlier.
Script mode versus module mode
There are two ways to run a file.
python path/to/file.pyruns the file as a script. Python puts the script's own directory at the front ofsys.path, and the file's__name__is"__main__". The file has no package context.python -m package.moduleruns the file as a module. Python locates it by importing it by name, throughsys.path. It puts the current working directory at the front ofsys.path, and sets__name__to"__main__". The file does know which package it belongs to.
The second form is what makes relative imports work in an entry point.
The relative import error
Take the shapes package from earlier and add a runnable file:
shapes/
__init__.py
circle.py
cli.py
util/
__init__.py
mathx.py# shapes/cli.py
from .circle import area
def main():
print(area(2))
if __name__ == "__main__":
main()Run it as a script from the project root:
python shapes/cli.py
ImportError: attempted relative import with no known parent packageThe script has no package, so the leading dot has nothing to refer to. Run it as a module instead:
python -m shapes.cli
12.56636Use dotted names, not slashes, and omit the .py suffix.
Running a package with `__main__.py`
You can run a whole package by adding a __main__.py file to it. python -m shapes imports the package, then runs shapes/__main__.py.
# shapes/__main__.py
from .cli import main
main()python -m shapes
12.56636You don't need an if __name__ == "__main__" guard here, because Python only runs this file when you run the package directly. Importing shapes never executes it.
Why `-m` is common in practice
- Reliable imports. The current directory is on
sys.path, so absolute imports such asfrom shapes.util.mathx import squareresolve from the project root. - Tools you installed. Running
python -m piporpython -m venvuses the interpreter you named, so the tool matches that interpreter's environment. - Standard library helpers. Examples are
python -m http.serverandpython -m json.tool.
Exercise
Exercise
A file tools/report.py contains from .helpers import load and sits in a package tools that has an __init__.py. Running python tools/report.py fails with an ImportError about a missing parent package. What command fixes it, and from which directory should you run it?
Show answer
Run python -m tools.report from the directory that contains the tools folder. In module mode, Python knows the file belongs to the tools package, so the relative import .helpers resolves.
Exercise
What file do you add so that python -m shapes works, and why does it need no __main__ guard?
Show answer
Add shapes/__main__.py. Python runs it only when the package is executed directly, and importing shapes never runs it, so a guard is unnecessary.