Python Language Parsing Command Line arguments Custom parser error message with argparse

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

You can create parser error messages according to your script needs. This is through the argparse.ArgumentParser.error function. The below example shows the script printing a usage and an error message to stderr 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 and args.bar is None:
    parser.error("--foo requires --bar. You did not specify bar.")

print "foo =", args.foo
print "bar =", args.bar

Assuming your script name is sample.py, and we run: python sample.py --foo ds_in_fridge

The script will complain with the following:

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


Got any Python Language Question?