The -m flag in Python stands for the “module name.” When you pass the -m flag followed by a module name to the Python interpreter, it will locate the module and execute its content as the __main__ module. This allows you to run a module directly from the command line.
If the -m flag is given to the Python statement, the first element of sys.argv will be the full path to the module file (while the module file is being found, the first item will be set to “-m”).
When -c is used with a statement on the command-line interface, it executes the Python statement(s) given as a command.
When a package name is provided instead of a normal module, the interpreter will execute the .main as the main module.
Why Use -m?
The -m flag is handy because it ensures the script runs with the correct package context, especially in scenarios where relative imports are used.
It also allows you to run Python standard library modules and third-party modules that provide command-line interfaces directly from the terminal.
Syntax
When invoking Python, you may specify any of these options,
python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]
When you call a command with -m module-name, the given module is located on the Python module path and executed as a script.
If you regularly install new modules, you notice one thing: every time you write an install command, you must see the -m flag.
Example 1: Running a Built-in Module
Suppose you want to run Python’s built-in HTTP server. You can do this using the -m flag with the http.server module. Open your command line or terminal and run:
python -m http.server or python3 -m http.server
This command starts an HTTP server on port 8000 by default, serving the contents of the current directory.
Example 2: Running a module from a Custom package
Our package might look something like this::
mypackage/
__init__.py
mymodule.py
Let’s say mymodule.py contains a simple function to print a message:
# mymodule.py
def hello():
print("Hello from mymodule!")
if __name__ == "__main__":
hello()
Running the Module:
python3 -m mypackage.mymodule
Example 3: Viewing a Module’s Help Information
For modules that support it, you can use the -m flag to view help information. For example, to see help information for the json.tool module:
python -m json.tool --help or python3 -m json.tool --help
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.