Robert
Robert

Reputation: 8663

How do I tell argparse to allow an argument only once?

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?

Upvotes: 1

Views: 1566

Answers (1)

RufusVS
RufusVS

Reputation: 4127

Following up on my comment:

import sys
import argparse

# args = sys.argv[1:]

args = "--out 1 --out 2 --out 3".split()

print(f"Input args: {args}")


parser = argparse.ArgumentParser()
parser.add_argument(
    "--out",
    action="append",
    required=True,
)

parsed = vars(parser.parse_args(args))

for key, val in parsed.items():
    if isinstance(val, list):
        print(f"{key} specified {len(val)} times!")
        parsed[key] = val[0]  # or val[-1]

print(parsed)

Upvotes: 2

Related Questions