What Is Python Main Function and How To Use It? – POFTUT

What Is Python Main Function and How To Use It?


We are new in python and have learned functions all ready. If we do not know the PYthon functions we can get information from http://www.poftut.com/define-use-functions-python-def/ . Now we know a lot about functions. But we see that standard functions name __main__ in most of the python applications. We want to understand this special function usage.

As we know applications in python can be run in different ways in different operating systems. In this tutorial I will follow Linux type but this will work for Windows operating too.

“Where Should I Start” asks Our App

When we specify to run some python file generally have extension .py  the python interpreter starts by default from running file from first line. This may hurt our application some times. We may want to specify start point specifically in later lines than first line of the script file.

Look Main Function Please

Python programming language provides special function named __main__ . main function simply specifies the start point of the application. __main__ also collects the user provided parameters and provides to the application. We will create a main function and call it with __main__ as seen below.

import sys 
 
def main(argv=None): 
    print("I am the MAIN") 
 
if __name__ == "__main__": 
    main(sys.argv)

Provide Arguments , Parameters To The Main Function

One of the most popular usage case of python application is providing parameters. We generally need to read parameters provided by the user and take action according to these parameters.

import sys 
 
def main(argv=None): 
    print("I am the MAIN and you chose") 
    print(argv) 
 
if __name__ == "__main__": 
    main(sys.argv)

When we execute we will get following result.

$ python3 mymain.py "This is a parameter"
Provide Arguments , Parameters To The Main Function
Provide Arguments , Parameters To The Main Function

As we can see the name of the application and given text is provided as parameters in a list format. We can easily select parameters with list indexing like below.

param1 = sys.argv[1]

LEARN MORE  Linux Bash Alias Command Tutorial

Leave a Comment