Using Python's -m Flag for Modules | Generated by AI
Yes, -m means run a module as a script. Let’s break this down with your examples:
python -m unittest
This tells Python:
- Look up the
unittestmodule (which is part of the standard library). - Run it as if it were a script (that’s what
-mdoes). -
That’s why you can do things like:
python -m unittest test_example.py python -m unittest discoverThis works even though you don’t have a standalone
unittestfile in your project — it’s a standard library module.
python -m pip
This is the same pattern:
- It looks up the
pipmodule (installed with Python). - Runs it as if it were
pipexecutable. - So
python -m pip install requestsis the “official” safe way to run pip, because it ensures you’re using the same Python interpreter’s pip that matches yourpython. (Sometimespipon your system might be pointing to a different Python installation, sopython -m pipavoids confusion.)
Difference from python test_xx.py
When you do:
python test_xx.py
you are running that specific file directly, not using unittest’s test discovery or runner.
- If
test_xx.pyhas aunittest.main()at the bottom, it will run tests. - But if you want Python to automatically discover all tests under a directory, you usually rely on
python -m unittest discover.
✅ Summary:
-m= run a module as a script.python -m unittestruns the standard library’s test runner.python -m pipensures pip corresponds to the same Python interpreter.python test_xx.pyjust runs one file, not the general test runner.
Would you like me to also show you how pytest handles this differently, since you might compare unittest vs pytest?