The -m (module name) flag in Python allows us to run a library module as a script. It enables the execution of modules that are part of a package or installed in your environment, using the module’s fully qualified name (dotted path).
When you pass the -m flag followed by a module name to the 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 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 a package name is provided instead of a normal module, the interpreter will execute the .main as the main module.
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 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.
Running a built-in module
Suppose you want to run a 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.
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
Using -m with installed packages
When you are upgrading your pip (package manager), you must have used the -m flag in the command like this:
python -m pip install --upgrade pip
This is safer than running pip directly, as it ensures the correct environment.
Debugging with -m
You can also use debugging tools like pdb in your while with the help of -m.
Let’s debug a script, debug_me.py:
a = 10 b = 0 print(a / b)
Now, let’s run the command below in your terminal:
python3 -m pdb debug_me.py
It will give us the output below:
Using the next() function, we can debug the file in the terminal, and that’s how we can use this flag.
Viewing a Module’s Help Information
For modules that support it, you can use the -m flag to view help information. For example, to view help information for json.tool module:
python -m json.tool --help or python3 -m json.tool --help
That’s it.