[파이썬] argparse add_mutually_exclusive_group() 사용

When creating command-line interfaces (CLIs) in Python, the argparse library is a great choice. It provides a convenient way of defining and parsing command-line arguments. One of the useful features of argparse is the ability to handle mutually exclusive arguments using the add_mutually_exclusive_group() method.

What are mutually exclusive arguments?

Mutually exclusive arguments are command-line arguments that cannot be used together. In other words, if one argument is specified, the other arguments in the group cannot be used and vice versa. This is often useful when you have options or flags that are mutually exclusive, meaning they represent different behaviors or configurations that cannot coexist.

How to use add_mutually_exclusive_group()?

Here’s an example of how to use add_mutually_exclusive_group() in Python with argparse:

import argparse

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

# Create a mutually exclusive group
group = parser.add_mutually_exclusive_group()

# Add arguments to the group
group.add_argument('-a', '--option-a', action='store_true', help='Enable option A')
group.add_argument('-b', '--option-b', action='store_true', help='Enable option B')

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

# Handle the selected option
if args.option_a:
    # Option A selected
    print("Option A is enabled.")
elif args.option_b:
    # Option B selected
    print("Option B is enabled.")
else:
    # Neither option selected
    print("No option selected.")

In the above example, we first create an ArgumentParser object. Then, we create a mutually exclusive group using the add_mutually_exclusive_group() method. Next, we add the desired arguments to the group using add_argument(). The action='store_true' argument makes the options behave as boolean flags, meaning they are either present (True) or absent (False).

Finally, we parse the command-line arguments using parse_args(). The selected option can be accessed through the corresponding attribute in the args object. The program then handles the selected option accordingly.

Conclusion

Using the add_mutually_exclusive_group() method in Python’s argparse library allows you to define and handle mutually exclusive command-line arguments effortlessly. It improves the user experience by ensuring that incompatible options cannot be used together.