Python m Flag: Meaning and Applications (2024)

Every command-line executable has some flags to configure it while it runs. Some of the popular flags include –help to get idea documentation about executable, -v to check the executable version, and -m flag to run a Python module. Although there are many other flags available, only a few of them are actually useful.

Python m flag runs the module as mentioned in __main__ module. -m flag requires the user to add an <module-name> as an argument right after it. After reading the argument, it checks the module in the sys.path and runs its content. Also, note that (.py) is not required while mentioning the module name in the command line.

You can use other supported characters from module names such as hyphen (-), under scroll (_), or dot (.) to call the specific modules. Some of the built-in modules are not available on this method because they are pre-compiled in C format and are not present in python modules.

Contents

What is Python m flag?

m Flag corresponds to module-name in simple terms. Using this command, you can run any module from your terminal directly without creating a code. This flexibility allows us to run scripts and helpful commands without ever touching or typing the code. In this post, we’ll have a look at all of these commands.

Moreover, the argument after -m is a module-name, and it’s searched in the sys.path for its location. You can include your current directory in the sys.path by using one additional -c flag.

How to use Python m flag?

Using the -m flag is way easier than actually running python. With a simple structure, you can execute your commands and print them to stdout. Following is the structure to use the m flag –

python -m <module-name>

Open your terminal and enter the above command in it. Make sure you replace <module-name> with available module names such as http.server, timeit, venv, and others. Also, if you have multiple pythons installed, you can run the m flag in the following way –

python -m flag <module-name>python3 -m flag <module-name>python3.6 -m flag <module-name>

Python m flag: Examples

Since many modules are available in Python, you can get thousands of ways to run the m flag. We’re going to have a look at a few of them which are used the most.

http server

Usage:

# Syntax: python -m http.server <PORT>python -m http.server 8000

Result:

http.server is a module that creates a directory hosting from your computer. This is a useful way of sharing files among your local network. By default, port 8000 is used to host the server, but you can customize it by sending additional port arguments.

This method creates a directory hosting of your current directory only. Your parent directories will not be accessible once you do that. So make sure you are in the desired directory to run this.

Python m Flag: Meaning and Applications (1)

Other computers over the network can access this server by going to their browser and entering {ServerIP:PORT} in place of URL.

timeit

Usage:

# Syntax: python -m timeit <loop-code>python -m timeit '"-".join(map(str,range(100)))'

Result:

50000000 loops, best of 5: 8.56 nsec per loop

Timeit is a great way of measuring time for small python codes. You can effectively measure execution time by using this simple m flag. The above code demonstrates a simple command-line way of measuring time for 50M loops.

The loop code can be simple for loop or a combination of map and range() functions.

venv

Virtual Environments are a great way of keeping your running environment clean from the global environment. This way you can install custom modules and create environmental variables without worrying about conflicts with other projects.

Usage:

# Syntax: python -m venv <path>python -m venv env

Result:

The python m flag command calls the venv module and set up a virtual environment at the mentioned path. In the above example, we’ve used ‘env’ as a path for creating a virtual environment.

Please note that you need to activate the virtual environment before using it.

Python m Flag: Meaning and Applications (3)

Trending

Python Setattr() Method For Setting Attributes of An Object

build

Usage:

# Syntax: python -m buildpython -m build

Result:

Building a module/source file is necessary for certain conditions. Normally, there is no easy way of doing it without the help of any module.

python -m build a way to generate source distribution and wheel files for your package. To use this flag, you need to install the PEP517 package builder module first by running

pip install build

Then, use the -m build command to generate files in dist/ directory.

compileall

Pyc format is handy to run the files fast. But the generation of pyc files is an automated process by default. But you can control it by compiling the pyc files on your own by using compileall python m flag.

Usage:

# Syntax: python -m compileall <file1> <file2> ...python -m compileall main.py

Result:

In the above example, we’ve compiled the main.py file to pyc format. After running this command, there should be a file named main.cpython-{Python-version}.pyc in __pycache__ folder.

cprofile

Usage:

# Syntax: python -m cProfile <file>python -m cProfile main.py

Result:

 24 function calls in 0.027 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.027 0.027 rea.py:1(<module>) 1 0.000 0.000 0.027 0.027 {built-in method builtins.exec} 21 0.027 0.001 0.027 0.001 {built-in method builtins.print} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

cProfile is a profiler used to calculate the total running time and total function calls within a code. As a result, this demonstrates how many times each function is called and which causes the most running time. This is a great way of debugging your spaghetti code!

ensurepip

Usage:

# Syntax: python -m ensurepip --upgradepython -m ensurepip --upgrade

Result:

pip is a package manager for python which can be used to install other modules. With coming updates to python, sometimes the pip needs to be updated too. This is where ensurepip comes into action.

This flag guarantees the correct pip for every python version and updates it accordingly. Moreover, if there are multiple pythons on your computer, you can update it by running single commands.

pip install

Usage:

# Syntax: python -m pip install <package-name>python -m pip install numpy

Result:

Sometimes, there are different versions of python and pip installed on your computer. This leads to the pain of installing new modules. There are many different pip versions, it’ll be hard to install modules into specific python environments.

This is where the m flag comes into play. Then, -m pip install ensures that the module is installed to executable python environment only. This way, you can take care of incorrect environment installs.

json.tool

JSON is a widely used data structure that can store hierarchical data. Most of the APIs use JSON response as a method to provide their services. But handling a minified JSON can be a head-scratcher for any developer.

Python m flag json.tool prettifies the JSON and views the data in a proper format.

Usage:

# Syntax: python -m json.tool <json-file>python -m json.tool file.json

Result:

file.json: {"foo":"lorem","bar":"ipsum"}Output: { "foo": "lorem", "bar": "ipsum"}

The above JSON file is prettified into readable format. You can use the “>” method in the command line to save this prettified JSON to file.

unittest

Unittest is a famous module in python used as the testing framework. In programming, testing is as much important as writing the code. Fortunately, there are easy ways to run the test in unittest once you create the test module.

Usage:

# Syntax: python -m unittest <test-module>python -m unittest test.py

Result:

test_isupper (__main__.TestStringMethod) ... oktest_split (__main__.TestStringMethod) ... oktest_upper (__main__.TestStringMethod) ... ok----------------------------------------------------------------------Ran 3 tests in 0.001sOK

The above m flag executes the unittest module and runs the test module to test different cases. In the above example, we’ve used 3 basic string tests.

zipfile

Zipfile is a useful module to handle zip files by using Python. You can compress the files and extract (unzip) them. This module has an executable m flag that can be used to compress any folder.

Usage:

# Syntax: python -m zipfile -c <zip-file-name> <directory>python -m -c folder.zip folder/

Result:

Python m flag zipfile is used to compress any directory into zipfile. This command uses the default compress_type and compresslevel configuration in creating zip files.

Popular now

Implementation of AIXI in Python

References

Final Words

Python is growing at a huge pace due to its simplicity and ease to use. -m flag is definitely an astonishing way to executing modules without even touching the python files. This post explained different ways through which you can run these flags.

If have any doubt regarding any of the command, let us know in the comments!

Trending Python Articles

  • Set Difference in Python: All You Need to Know
  • Python Setattr() Method For Setting Attributes of An Object
  • Implementation of AIXI in Python
  • How To Use the Webull Package in Python
Python m Flag: Meaning and Applications (2024)

FAQs

Python m Flag: Meaning and Applications? ›

What is Python m flag? m Flag corresponds to module-name in simple terms. Using this command, you can run any module from your terminal directly without creating a code. This flexibility allows us to run scripts and helpful commands without ever touching or typing the code.

What is Python M flag used for? ›

The -m flag makes sure that you are using the pip that's tied to the active Python executable. It's good practice to always use -m , even if you have just one global version of Python installed from which you create virtual environments.

What does M mean in pip? ›

7 -m pip means you are executing pip for your interpreter located at /usr/bin/python3. 7 . You can read the docs on -m if you're unfamiliar with the flag and how it works (it's very handy).

What does M mean in CMD? ›

-c command Specify the command to execute (see next section). This terminates the option list (following options are passed as arguments to the command). -m module-name Searches sys.

What does __ main __ mean in Python? ›

In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.

What is flag for pip install? ›

The --user flag to pip install tells Pip to install packages in some specific directories within your home directory. This is a good way to have your own default Python environment that adds to the packages within your system directories, and therefore, does not affect the system Python installation.

What is M terminal? ›

Airplanes will either deplane at the Contact Pier (domestic & some international flights) or STB (international flights). You can only get to the Contact Pier or STB via the MTB which is where you do your check-in, baggage collection, immigration and customs. This MTB is what is commonly known as "Terminal M".

What does M mean in Linux? ›

Control M ( ^M) characters are introduced when you use lines of text from a windows computer to Linux or Unix machine. Most common reasons are when you directly copy a file from a windows system or submit form data copied and pasted from a windows machine.

What are flags Python? ›

flags defines a distributed command line system, replacing systems like getopt() , optparse , and manual argument processing. Rather than an application having to define all flags in or near main() , each Python module defines flags that are useful to it.

What is __ init __ py? ›

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

What is def __ init __( self in Python? ›

In this code: class A(object): def __init__(self): self.x = 'Hello' def method_a(self, foo): print self.x + ' ' + foo. ... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not.

What is the purpose of __ init __? ›

The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

Why do we use flag in programming? ›

Flag variable is used as a signal in programming to let the program know that a certain condition has met. It usually acts as a boolean variable indicating a condition to be either true or false.

What is flag variable in Python? ›

Flag variables are the same for all languages, whether it's RUBY, Python, Javascript or C++. A flag variable is usually given one value, 0 or 1 , True or False . It's used as a Boolean variable where the result toggles between 0 (False) and 1 (True) or as used by the programmer.

How do you use Boolean flags in Python? ›

The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False .
...
The and Boolean Operator.
ABA and B
TrueFalseFalse
FalseFalseFalse
2 more rows

What is flag in programming? ›

In programming, a flag is a predefined bit or bit sequence that holds a binary value. Typically, a program uses a flag to remember something or to leave a sign for another program.

Top Articles
Latest Posts
Article information

Author: Horacio Brakus JD

Last Updated:

Views: 6171

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Horacio Brakus JD

Birthday: 1999-08-21

Address: Apt. 524 43384 Minnie Prairie, South Edda, MA 62804

Phone: +5931039998219

Job: Sales Strategist

Hobby: Sculling, Kitesurfing, Orienteering, Painting, Computer programming, Creative writing, Scuba diving

Introduction: My name is Horacio Brakus JD, I am a lively, splendid, jolly, vivacious, vast, cheerful, agreeable person who loves writing and wants to share my knowledge and understanding with you.