How do I tell argparse that I want to allow a command line argument only once?
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--out",
required=True,
)
parsed = parser.parse_args(sys.argv[1:])
print(f"out: {parsed.out}")
If I call this code like this:
python3 argparsetest.py --out 1 --out 2 --out 3
it prints
out: 3
But I would rather have it error out telling the user that the --out
argument can only be used once.
I looked at the nargs
option, but that says how many following arguments should be considered for --out
, not how often I can pass the --out
.
There is the required
option which forces the user to supply the argument (at least once), but I'm looking for limiting the upper number of how often the argument can be used, not the lower.
I've seen Only one command line argument with argparse but this is from 2013 and I am hoping that there is an easier way to do this now.
How can I limit the number of uses of a command line flag?