import argparse
Create an ArgumentParser object
parser = argparse.ArgumentParser()
Add a positional argument with nargs=’+’ to accept a list of values
parser.add_argument(‘numbers’, nargs=’+’, type=int, help=’List of numbers’)
Parse the command-line arguments
args = parser.parse_args()
Access the list of numbers provided as input
numbers = args.numbers
Perform some operation on the list of numbers
sum_of_numbers = sum(numbers) average_of_numbers = sum(numbers) / len(numbers)
Print the results
print(f”Sum of numbers: {sum_of_numbers}”) print(f”Average of numbers: {average_of_numbers}”) ```
In this example, we are using the argparse
module in Python to handle command-line arguments, specifically a list of numbers as input. We create an ArgumentParser
object and add a positional argument named “numbers”. By setting nargs='+'
, we allow the user to provide multiple values for this argument.
After parsing the command-line arguments using parser.parse_args()
, we can access the list of numbers provided by accessing the args.numbers
attribute. We then perform some operations on the list, such as calculating the sum and average of the numbers. Finally, we print the results.
To use this script, you can run it from the command line and provide a list of numbers as arguments. For example, python script.py 1 2 3 4 5
will calculate the sum and average of the numbers 1, 2, 3, 4, and 5.