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
parse.errorandparser.exitmethods. You can customize those. The message to theinvalid intcase could be changed by writing atypefunction that raises aargparse.ArgumentTypeErrorwith the custom message.