Issue
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
Solution
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)
Answered By - Carlos Correa Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.