Sub topic 11
Running modules and packages with python -m
This chapter assumes you know how import finds modules through sys.path, how a package is laid out with __init__.py, and how relative imports and the __main__ guard work. It builds on those to explain why python -m exists and when to prefer it over running a file path.
Two ways to start Python code
You can start a program in two ways:
python shapes/circle.py
python -m shapes.circleThe first form gives Python a file path. The second gives it a module name, written as a dotted import name. Python then finds the module the same way import would and runs it.
The difference matters because the way you start a file decides how the import system sees it. The interpreter sets three things differently:
| Row | `python path/to/file.py` | `python -m pkg.mod` |
|---|---|---|
| Name given | A file path | A dotted module name |
| `sys.path[0]` | The directory containing the file | The current working directory |
| `__name__` | `"__main__"` | `"__main__"` |
| `__package__` | `None` | `"pkg"` (the parent package) |
| Parent packages imported first | No | Yes |
| Relative imports work | No | Yes |
Both forms set __name__ to "__main__", so the guard from the earlier chapter works either way. The __package__ value is what separates them. Relative imports resolve against __package__.
See the difference
Save this file as whereami.py in an empty directory:
# whereami.py
import sys
print("name:", __name__)
print("package:", repr(__package__))
print("sys.path[0]:", repr(sys.path[0]))Run it as python whereami.py, then as python -m whereami. In both runs __name__ is __main__. Under the script form __package__ is None. Under -m it is an empty string, because whereami is a top-level module with no parent package. In the first run sys.path[0] is the script's directory. In the second it is the directory you ran the command from.
Why relative imports need -m
Recall shapes/circle.py from the package example, which uses from .util.mathx import square. Run it by path:
python shapes/circle.pyIt fails with ImportError: attempted relative import with no known parent package. Python started the file as a loose script, so __package__ is None. The leading dot means "the package that contains this module", and there is no such package to resolve against.
Run it as a module and the import works, because Python knows the file is shapes.circle:
python -m shapes.circleRun this from the directory that contains shapes/, not from inside it. With -m, the first sys.path entry is your current directory, so that directory is where Python looks for shapes.
Running a whole package with `__main__.py`
If you give -m a package name, Python looks inside the package for a file named __main__.py and runs it. This is how you make a package executable. Add this file to the running example:
# shapes/__main__.py
import sys
from . import circle_area
def main(argv):
if len(argv) != 2:
print("usage: python -m shapes RADIUS", file=sys.stderr)
return 2
print(f"{circle_area(float(argv[1])):.2f}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))Then run it from the project root:
python -m shapes 2This prints 12.57. Three details are worth noting:
from . import circle_areauses the name thatshapes/__init__.pyre-exports. The public interface from the previous chapter is what the command-line entry point uses.maintakesargvand returns an exit code. That keeps it testable without starting a subprocess.sys.exit(main(sys.argv))passes the return value to the operating system as the process exit status. This is what shell scripts and CI check.
If shapes has no __main__.py, Python reports No module named shapes.__main__; 'shapes' is a package and cannot be directly executed.
The double-import warning
Try python -m shapes.circle with the __init__.py from the previous chapter and, assuming circle.py has a __main__ guard, you may see a RuntimeWarning. The message says 'shapes.circle' found in sys.modules after import of package 'shapes', but prior to execution of 'shapes.circle'.
The cause is the order of events. Python imports the parent package shapes first. Its __init__.py runs from .circle import area, which loads shapes.circle into sys.modules. Then -m executes circle.py a second time under the name __main__. The file's top-level code runs twice, and you get two separate module objects, one named shapes.circle and one named __main__. Classes defined in the file exist twice, so isinstance checks between them fail.
The usual fix is to run the package instead, with python -m shapes, and keep the entry-point code in __main__.py. A module that the package's __init__.py imports should not be used as a -m target.
Standard-library commands that use -m
Many tools ship as runnable modules. Using python -m with them has an extra benefit: the tool runs under the exact interpreter you chose, not whichever executable is first on PATH.
| Command | Purpose |
|---|---|
| `python -m venv .venv` | Create a virtual environment |
| `python -m pip install requests` | Install into this interpreter's environment |
| `python -m http.server 8000` | Serve the current directory over HTTP |
| `python -m json.tool data.json` | Pretty-print JSON |
| `python -m unittest discover` | Find and run tests |
| `python -m timeit "sum(range(100))"` | Time a snippet |
python -m pip is the reliable way to avoid installing into the wrong environment. It is the case where a pip on PATH belongs to a different Python than the python you run.
Other points about -m
- Give
-ma module name, not a file name.python -m shapes/circle.pyfails, because the dots and slashes are interpreted as a module name. - Python 3.11 added the
-Poption and thePYTHONSAFEPATHenvironment variable. They stop Python from putting the script directory or current directory at the front ofsys.path. This closes the shadowing problem where a strayrandom.pyin your working directory replaces the standard library module. - Under
-m,sys.argv[0]is the full path of the module file, not its name. The arguments after the module name are passed through unchanged. - To mimic
-mfrom Python code,runpy.run_module("shapes", run_name="__main__")runs a module by name.runpy.run_pathruns a file path. Test suites and tooling use these.
Choosing between the two forms
Use a file path for a single standalone script with no imports from your own project. Use python -m when the code lives inside a package, uses relative imports, or you want the project root to be the import base. For a project you install, a console script entry point is more convenient for users, but python -m yourpackage remains a dependable way to run it during development.
Exercise
A project has app/__init__.py and app/tools/clean.py. The file clean.py contains from ..config import SETTINGS. You are in the project root, the directory that contains app/. Running python app/tools/clean.py gives "attempted relative import with no known parent package". What command fixes it, and why does it work?
Show answer
Run python -m app.tools.clean. With -m, Python locates app.tools.clean through sys.path, imports the parent packages app and app.tools, and sets __package__ to app.tools. The .. in from ..config import SETTINGS can then resolve to app.config. Running by path leaves __package__ as None, so the dots have nothing to resolve against.
Exercise
You add __main__.py to a package named tool and run python -m tool --help. Where does the code run, and what does sys.argv contain?
Show answer
Python imports the package tool (running its __init__.py), then executes tool/__main__.py with __name__ set to "__main__". sys.argv[0] is the path of __main__.py, and sys.argv[1:] is ["--help"].