Custom parser error message with argparse

suggest change

You can create parser error messages according to your script needs. argparse.ArgumentParser.error prints a usage line and an error message to stderr, then exits. The script below does that when --foo is given but not --bar.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo')
parser.add_argument('-b', '--bar')
args = parser.parse_args()
if args.foo is not None and args.bar is None:
    parser.error('--foo requires --bar. You did not specify bar.')

When the script is sample.py and you run python sample.py --foo ds_in_fridge, stderr is:

usage: sample.py [-h] [-f FOO] [-b BAR]
sample.py: error: --foo requires --bar. You did not specify bar.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents