PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How to set custom error messages for argparse python module

 November 14, 2022     argparse, error-handling, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing