Open In App

What is the use of Python -m flag?

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python, a versatile and widely used programming language, provides a plethora of features and command-line options to facilitate various tasks. One such option that might pique your interest is the -m switch. In this article, we will explore what Python -m is and how it can be used, accompanied by four illustrative code examples.

What is Python -m?

The -m switch in Python is a command-line option that allows you to run a module as a script. This means you can execute Python code directly from the command line without the need for an external script file. By using -m, you can invoke Python modules as standalone programs.

Python -M Examples

Below are some of the ways by which we can understand about Python -m command in Python:

  • Running Python Modules
  • A module within a Package
  • Running Built-in Modules

Running Python Files

In this example, the -m switch allows us to run the example_module as a script, passing the argument “World” to the greet function. Consider a Python module named example_module. To execute it using the -m switch, create a file named example_module.py with the following content:

Python3




# example_module.py
def greet(name):
    print(f"Hello, {name}!")
 
if __name__ == "__main__":
    import sys
    greet(sys.argv[1])


Now, run the module using the -m switch:

python -m example_module World

Output:

Screenshot-2024-02-01-132809

Module within a Package

Let’s extend our understanding to modules within packages. Consider a package named example_package with a module submodule:

Python3




# example_package/submodule.py
def print_message():
    print("This is a submodule.")
 
if __name__ == "__main__":
    print_message()


To run the submodule using -m, use the following command:

python -m example_package.submodule

Output:

Screenshot-2024-02-01-132916

The -m switch enables us to execute modules within packages, specifying the package path with dots.

Running Built-In Modules

The -m switch is not limited to user-defined modules; it can also be used with built-in modules. For instance, you can run the timeit module to measure the execution time of a code snippet:

Python3




python -m timeit "print('Hello, World!')"


This will display the time taken to execute the specified code snippet.

Output:

Screenshot-2024-02-01-133030

Conclusion

In conclusion, the Python -m switch is a powerful tool that allows you to run modules as scripts directly from the command line. Whether it’s user-defined modules, modules within packages, or built-in modules, the -m switch enhances the flexibility of Python’s command-line interface. Experiment with this feature to streamline your development and testing processe



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads