Python “-m” flag Example and How to Use It

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.

Running a Built-in Module

Example 2: Running a module from a Custom package

Our package might look something like this::

mypackage/  
   __init__.py 
   mymodule.py

Directory Structure

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

Running a module from a Custom package

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

Viewing a Module's Help Information

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.