Using argparse in Python: Command-Line Arguments

The argparse module in Python is a powerful tool for handling and parsing command-line arguments when running a program. It allows you to easily define the required parameters and options for your program and provides flexible mechanisms for reading and using them.

Here are the steps to use the argparse module:

  1. Import the argparse module: Start your program by importing the argparse module.

  2. Define the ArgumentParser object: Create an ArgumentParser object to define the required parameters and options for your program.

  3. Add arguments: Use the .add_argument() method of the ArgumentParser object to add the necessary parameters and options for your program. Each argument can have a name, data type, description, and various other attributes.

  4. Parse arguments: Use the .parse_args() method of the ArgumentParser object to parse the arguments from the command-line and store them in an object.

  5. Use the arguments: Use the values stored in the parsed object from the previous step to perform actions corresponding to the provided options from the command-line.

Example: Here's a simple example of how to use argparse to calculate the sum of two numbers from the command-line:

import argparse

# Define the ArgumentParser object
parser = argparse.ArgumentParser(description='Calculate the sum of two numbers.')

# Add arguments to the ArgumentParser
parser.add_argument('num1', type=int, help='First number')
parser.add_argument('num2', type=int, help='Second number')

# Parse arguments from the command-line
args = parser.parse_args()

# Use the arguments to calculate the sum
sum_result = args.num1 + args.num2
print(f'The sum is: {sum_result}')

When running the program with arguments, for example: python my_program.py 10 20, the output will be: The sum is: 30, and it will display the sum of the two numbers provided from the command-line.