[파이썬] argparse ArgumentTypeError 사용

In Python, the argparse module is widely used for parsing command-line arguments and generating user-friendly command-line interfaces. It provides a flexible and powerful way to handle command-line input.

One useful feature of argparse is the ability to define custom error messages for invalid argument values. This can be achieved by utilizing the argparse.ArgumentTypeError class.

What is ArgumentTypeError?

ArgumentTypeError is an exception class provided by argparse to handle argument value type errors. It can be raised when the value provided for an argument does not match the expected type.

How to use ArgumentTypeError?

Let’s say we have a script that takes a filename as a command-line argument and we want to ensure that the provided filename has the .txt extension. If the user provides a filename without the .txt extension, we want to display a customized error message.

Here’s an example of how to use ArgumentTypeError to achieve this:

import argparse

def validate_filename(filename):
    if not filename.endswith('.txt'):
        raise argparse.ArgumentTypeError("Invalid filename. Please provide a file with '.txt' extension.")
    return filename

parser = argparse.ArgumentParser()
parser.add_argument('filename', type=validate_filename, help='Path to a text file')
args = parser.parse_args()

# Use the filename argument
print(f"Processing file: {args.filename}")

In the above example, we define a helper function validate_filename that checks if the provided filename ends with the .txt extension. If the filename is not valid, we raise argparse.ArgumentTypeError with a custom error message.

The type parameter of add_argument is set to validate_filename, which ensures that the provided value is validated using our custom function.

If the user provides an invalid filename, argparse will handle the exception and display the custom error message along with usage information.

Conclusion

The ArgumentTypeError class in the argparse module provides an easy way to handle type errors in command-line argument parsing and display customized error messages to the user. By utilizing this class, you can improve the user experience of your command-line interface and provide helpful feedback.