Custom parser error message with argparse
suggest changeYou 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents