2

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

1
  • The argparse docs tell us that errors (at least most) go through the parse.error and parser.exit methods. You can customize those. The message to the invalid int case could be changed by writing a type function that raises a argparse.ArgumentTypeError with the custom message. Commented Mar 5, 2022 at 16:25

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.