Malav Patel

Python Argparse

The argparse module in Python provides an easy way to write user-friendly command-line interfaces. It allows you to define arguments and options that can be used to call a function from the command line.

Example main.py File

Here is an example of a simple main.py file that uses argparse to define a required positional argument echo and two optional arguments: name and age. The greet function takes these arguments and prints out a greeting message, echoing the input.

import argparse

def greet(echo, name = None, age = None):
    if name is None:
        name = "Stranger"
    if age is None:
        age = "__"
    print(f"Hello, {name}! You are {age} years old. Here is what you wanted me to echo: {echo}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Greet someone")
    parser.add_argument("echo", type=str, help="Required Positional Argument text to echo")
    parser.add_argument("-n", "--name", type=str, help="Optional argument your name")
    parser.add_argument("-a", "--age", type=int, help="Optional argument your age")
    args = parser.parse_args()
    greet(args.echo, args.name, args.age)

In this example, we define the greet function, which takes two arguments: name and age. We then create an ArgumentParser object and add two arguments: name and age. We use the type parameter to specify the type of each argument (str for name and int for age). Finally, we parse the command-line arguments using parse_args() and pass the parsed arguments to the greet function.

Example Bash Script

Here is an example bash script that runs the main.py file with some sample arguments:

$ python main.py "Echo me" -n "John Doe" -a 30
Hello, John Doe! You are 30 years old. Here is what you wanted me to echo: Echo me

This script simply runs the main.py file with the required argument "Echo me" and optional arguments -n "John Doe" and -a 30. When you run this script, it outputs the person’s name and age followed by the echo.