[파이썬] argparse 여러 값 받기 (varargs)

Argparse is a powerful Python module for parsing command-line arguments. It allows you to define the arguments your program can accept and handles the parsing process for you. One useful feature of Argparse is the ability to accept multiple values for a single argument, also known as varargs. In this blog post, we will explore how to use varargs with Argparse in Python.

Why use varargs?

In some cases, you may want to allow users to provide multiple values for a particular argument. For example, imagine you are building a command-line tool that calculates the average of a list of numbers. Instead of asking the user to enter each number individually, it would be more convenient to allow them to provide multiple values at once. Varargs allow you to achieve this flexibility by accepting an arbitrary number of values for an argument.

Example usage

Let’s see how to implement varargs using Argparse in Python:

import argparse

# Create an ArgumentParser object
parser = argparse.ArgumentParser()

# Add the argument that accepts multiple 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
numbers = args.numbers

# Perform some operation on the numbers (e.g., calculate average)
average = sum(numbers) / len(numbers)

# Print the result
print(f'Average: {average}')

In this example, we create an ArgumentParser object and add an argument called ‘numbers’ using the add_argument method. We set nargs='+' to indicate that this argument accepts one or more values. The type=int parameter ensures that the provided arguments are interpreted as integers.

After parsing the command-line arguments, the multiple values are stored in a list called numbers. We can then perform any operations or calculations on this list.

To use this program, you would run it from the command line and provide multiple numbers as arguments. For example:

$ python average.py 4 6 2 9 5
Average: 5.2

Conclusion

Using varargs with Argparse in Python allows you to accept multiple values for a single argument, providing a more efficient and user-friendly way to interact with your command-line programs. By leveraging the power of Argparse, you can easily handle complex argument parsing scenarios. Varargs can enhance the flexibility and usability of your programs, making them more versatile and user-friendly.