Use Main Function In Python Like C

10 Jul 2024 - Syed Muhammad Shahrukh Hussain

You can use a main function in python just like C with command line arguments. The main function executes by default for the script and accepts two arguments (argc, argv). The argument argc is the arguments count and argv has the python List of command line arguments.

The main function mechanism is adopted from python top level code environment __main__. Every module in python has a name. By default when you execute a python code it is within the __main__ module. And if we query the name of the module it comes up to be __main__ as predicted.

So placing an if condition for the module name allows a script to execute a code conditionally if the module name is __main__.

import sys
def main(argc, argv):
    print(argc,type(argv))

if __name__ == '__main__':
    sys.exit(main(len(sys.argv), sys.argv))