How to Use the Python Main Function with Arguments?

Recently in one of my projects for my USA clients, I came across a scenario where I needed to use main function with arguments in Python. In this tutorial, I will explain how to effectively use the Python main function with arguments. I will cover the essentials of the main function, delve into handling arguments, and provide practical examples and screenshots.

Python Main Function

The main function in Python serves as the entry point of a script. While Python does not have a mandatory main function like some other programming languages, defining a main function is a best practice for writing clean and modular code. This function typically contains the core logic of your script and is executed when the script is run directly.

Read How to Use the trim() Function in Python?

Define the Main Function

To define a main function in Python, you use the following syntax:

def main():
    # Your main logic here
    pass

if __name__ == "__main__":
    main()

The if __name__ == "__main__": block ensures that the main function is executed only when the script is run directly, not when it is imported as a module in another script.

Check out How to Use the Floor() Function in Python?

Handle Arguments in the Main Function

Arguments allow you to pass data to your script from the command line. This is particularly useful for making your scripts more dynamic and flexible.

1. Use the sys Module

The sys module in Python provides access to command-line arguments through sys.argv. The first element of sys.argv is the script name, and the subsequent elements are the arguments passed to the script.

Here is an example of a main function that accepts arguments:

import sys

def main():
    if len(sys.argv) != 3:
        print("Usage: python script.py <arg1> <arg2>")
        sys.exit(1)

    arg1 = sys.argv[1]
    arg2 = sys.argv[2]

    print(f"Argument 1: {arg1}")
    print(f"Argument 2: {arg2}")

if __name__ == "__main__":
    main()

Read How to Use the round() Function in Python?

2. Use the argparse Module

For more complex argument parsing, the argparse module is recommended. It provides a more robust way to handle command-line arguments.

Here is an example using argparse:

import argparse

def main():
    parser = argparse.ArgumentParser(description="Process some integers.")
    parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))

if __name__ == "__main__":
    main()

In this example, the script can either sum or find the maximum of a list of integers based on the provided arguments.

Check out How to Use the repeat() Function in Python?

Use the Python Main Function with Arguments

Let us see some practical examples of Python’s main function with arguments.

Example 1: Greet Script

Let’s create a script that greets a user based on their name and city. This example demonstrates how to handle string arguments.

import argparse

def main():
    parser = argparse.ArgumentParser(description="Greet the user.")
    parser.add_argument('name', type=str, help='The name of the user')
    parser.add_argument('city', type=str, help='The city of the user')

    args = parser.parse_args()
    print(f"Hello, {args.name} from {args.city}!")

if __name__ == "__main__":
    main()

To run this script, you would use the command:

python example.py John NewYork

This would output:

Hello, John from New York!

You can look at the output in the s screenshot below.

Use the Python Main Function with Arguments

Read How to Use the ceil() Function in Python?

Example 2: Simple Calculator

Now, let’s create a simple calculator script that can add, subtract, multiply, and divide two numbers.

import argparse

def main():
    parser = argparse.ArgumentParser(description="Simple calculator.")
    parser.add_argument('num1', type=float, help='First number')
    parser.add_argument('num2', type=float, help='Second number')
    parser.add_argument('operation', type=str, choices=['add', 'subtract', 'multiply', 'divide'], help='Operation to perform')

    args = parser.parse_args()

    if args.operation == 'add':
        result = args.num1 + args.num2
    elif args.operation == 'subtract':
        result = args.num1 - args.num2
    elif args.operation == 'multiply':
        result = args.num1 * args.num2
    elif args.operation == 'divide':
        if args.num2 == 0:
            print("Error: Division by zero is not allowed.")
            return
        result = args.num1 / args.num2

    print(f"The result of {args.operation}ing {args.num1} and {args.num2} is {result}")

if __name__ == "__main__":
    main()

To run this script, you would use commands like:

python calculator.py 10 5 add
python calculator.py 10 5 subtract
python calculator.py 10 5 multiply
python calculator.py 10 5 divide

You can look at the output in the s screenshot below.

How to Use the Python Main Function with Arguments

Check out How to Use the Python pop() Function?

Example 3: File Reader

Finally, let’s create a script that reads a file and prints its contents. This example shows how to handle file paths as arguments.

import argparse

def main():
    parser = argparse.ArgumentParser(description="Read a file and print its contents.")
    parser.add_argument('filepath', type=str, help='The path to the file')

    args = parser.parse_args()

    try:
        with open(args.filepath, 'r') as file:
            contents = file.read()
            print(contents)
    except FileNotFoundError:
        print(f"Error: The file at {args.filepath} was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    main()

To run this script, you would use the command:

python filereader.py example.txt

Check out How to Use wait() Function in Python?

Conclusion

In this tutorial, I explained how to use the Python main function with arguments. I discussed Python’s main function, defining the main function, and handling arguments in the main function using sys module and argparse module. I also discussed three practical examples.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.