I want to generate custom error messages for particular usage errors in my command-line program that uses the argparse
library. I know I can override the general presentation of the error by subclassing argparse.ArgumentParser
:
class HelpParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
sys.exit(2)
parser = HelpParser(... ...)
args = parser.parse_args()
But when my error
method is called, message
has already been formatted by the library. For example,
> python prog.py old stuff
usage: prog [-h] {hot,cold,rain,snow} ...
prog: error: argument subparser: invalid choice: 'old' (choose from u'hot', u'cold', u'rain', u'snow')
How can I change how the stuff after error:
is presented, for instance to
usage: prog [-h] {hot,cold,rain,snow} ...
error: 'old' is not a valid option. select from 'hot', 'cold', 'rain', 'snow'
?
Looking at the source code, you could over-ride
this particular
error message by overriding this method:The issue is that if you wanted to override all possible error messages, you'd have to basically re-write this module. All the various error messages are pre-formatted throughout -in the various methods that detect each type of error.