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:
-
Import the
argparse
module: Start your program by importing theargparse
module. -
Define the
ArgumentParser
object: Create anArgumentParser
object to define the required parameters and options for your program. -
Add arguments: Use the
.add_argument()
method of theArgumentParser
object to add the necessary parameters and options for your program. Each argument can have a name, data type, description, and various other attributes. -
Parse arguments: Use the
.parse_args()
method of theArgumentParser
object to parse the arguments from the command-line and store them in an object. -
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.