[파이썬] argparse 인수의 choices 속성 활용

When creating command-line interfaces (CLIs) in Python, the argparse module is a powerful tool for parsing command-line arguments and options. One useful feature of argparse is the choices attribute, which allows you to restrict the valid values that can be provided for a specific argument.

Let’s explore how to use the choices attribute in argparse with a simple example.

import argparse

# Create the ArgumentParser object
parser = argparse.ArgumentParser(description='Example CLI')

# Define the argument with choices
parser.add_argument('mode', choices=['option1', 'option2', 'option3'], help='Choose a mode')

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

# Access the chosen mode
if args.mode == 'option1':
    print('Option 1 selected')
elif args.mode == 'option2':
    print('Option 2 selected')
elif args.mode == 'option3':
    print('Option 3 selected')

In the above code, we create an ArgumentParser object and define an argument called mode. We specify the choices attribute as ['option1', 'option2', 'option3'], which means that the user can only provide one of these three values for the mode argument.

When running the script, the user must provide a valid choice for the mode argument. If an invalid choice is provided, argparse will raise an error and display an appropriate message.

Here’s an example of running the script with different choices:

$ python script.py option1
Option 1 selected

$ python script.py option2
Option 2 selected

$ python script.py invalid_option
usage: script.py [-h] {option1,option2,option3}
script.py: error: argument mode: invalid choice: 'invalid_option' (choose from 'option1', 'option2', 'option3')

By using the choices attribute, we can enforce a specific set of values for an argument, making our CLI more robust and user-friendly. Additionally, if you provide a help string for the argument, it will be displayed when the user runs the script with the --help or -h option.

In summary, the choices attribute in argparse allows you to define a limited set of valid values for a command-line argument. This can be useful in ensuring that users provide correct inputs and improving the overall experience of your CLI application.