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


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 and is None:
    parser.error("--foo requires --bar. You did not specify bar.")

print "foo =",
print "bar =",

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

The script will complain with the following:

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