Deadjim
Deadjim

Reputation: 59

How to set custom error messages for argparse python module

I want to change default message for errors caused by typing wrong argument value or typing argument without any value.

I have code test.py:

import argparse


parser = argparse.ArgumentParser()

parser.add_argument('-n',
                    '--number',
                    type=int,
                    help='Specify a number to print',
                    required=False)

args = parser.parse_args()


if __name__ == "__main__":
    if not args.number:
        print("Hello")
    else:
        print(args.number)

And when i'm typing python test.py i have output Hello

When i'm typing python test.py --number 1 i have output 1

But when i'm typing python test.py --number i've got:
test.py: error: argument -n/--number: expected one argument

But i want to have custom message in that output like "Please write number to print" - How i can "catch" error from argparser and customize the message of it

Also i want to have same error message when i'll get invalid int value

like in example:
python test.py --number k
test.py: error: argument -n/--number: invalid int value: 'k'

And i want:
python test.py --number k
Please write number to print
python test.py --number
Please write number to print

Upvotes: 2

Views: 1670

Answers (2)

Maxim Kopylov
Maxim Kopylov

Reputation: 11

In a similar vein to Carlos Correa's answer, you can instead set the parser object's error method directly using MethodType.

import argparse, types

parser = argparser.ArgumentParser()

def custom_error(self, message):
    raise Exception('Your message')

# Set the object's error method directly
parser.error = types.MethodType(custom_error, parser)

This can avoid some of the clunkiness of creating a new class specifically for this purpose.

Upvotes: 1

Carlos Correa
Carlos Correa

Reputation: 76

To do what you want, you can override the error method of the ArgumentParser class, you can see the argparse source code at https://github.com/python/cpython/blob/3.10/Lib/argparse.py

#instead of doing this
parser = argparser.ArgumentParser()

#do this

class CustomArgumentParser(argparse.ArgumentParser)
    def error(self, message):
        raise Exception('Your message')

#then use the new class

parser = CustomArgumentParser(exit_on_error=False)

Upvotes: 4

Related Questions