[파이썬] argparse 인수의 부울 처리

Python’s argparse module is a powerful tool for parsing command-line arguments and options. While it provides various options for handling different types of arguments, it doesn’t have a built-in way to handle boolean arguments. In this blog post, we’ll explore different approaches to handle boolean arguments using argparse in Python and discuss their pros and cons.

Approach 1: Using store_true and store_false

The simplest way to handle boolean arguments is by using the store_true and store_false action options provided by argparse. Here’s an example:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--flag', action='store_true', help='Set the flag')
args = parser.parse_args()

if args.flag:
    print("Flag is set")

In this example, if the --flag argument is passed while running the script, the value of args.flag will be True. Otherwise, it will be False. However, this approach has a limitation that it doesn’t allow passing a false value explicitly.

Approach 2: Using choices and type

To overcome the limitation of the previous approach, we can define a custom argument type and use the choices option to specify our boolean options explicitly. Here’s an example:

import argparse

def bool_arg(value):
    if value in ['True', 'true', 'Yes', 'yes', 'Y', 'y', '1']:
        return True
    elif value in ['False', 'false', 'No', 'no', 'N', 'n', '0']:
        return False
    else:
        raise argparse.ArgumentTypeError('Invalid boolean value')

parser = argparse.ArgumentParser()
parser.add_argument('--flag', type=bool_arg, choices=['True', 'False'], default=False, help='Set the flag')
args = parser.parse_args()

if args.flag:
    print("Flag is set")

In this approach, we define a custom bool_arg function that converts the string value to a boolean. We then use this function as the type of the argument and specify the allowed choices explicitly.

Approach 3: Using true and false flags

Another approach to handle boolean arguments is by using separate flags for true and false values. This approach provides more flexibility and allows explicitly passing both true and false values. Here’s an example:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--enable', action='store_true', help='Enable the feature')
parser.add_argument('--disable', action='store_true', help='Disable the feature')
args = parser.parse_args()

if args.enable:
    print("Feature is enabled")
elif args.disable:
    print("Feature is disabled")

In this approach, we have separate --enable and --disable flags. Only one of them can be used at a time. If both flags are omitted, the default value will be False.

Conclusion

Handling boolean arguments in argparse can be done using different approaches, each with its own advantages and limitations. The choice of approach depends on the specific requirements of your application. Whether you use the store_true, store_false, custom type, or separate flags, argparse provides the flexibility to handle boolean arguments efficiently in your Python scripts.