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.
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.
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.
build
Usage:
# Syntax: python -m build
python -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 --upgrade
python -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) ... ok test_split (__main__.TestStringMethod) ... ok test_upper (__main__.TestStringMethod) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.001s OK
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.
References
- Timeit: Measure execution time of small code snippets
- http.server: HTTP Server Module
- JSON Module: JSON encoder and decoder
- venv: Creation of virtual environments
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!