Noam Yulzari
Noam Yulzari

Reputation: 110

Passing optional number of arguments to a flag Python argparse

I want to be able to pass to my python script 1 or 2 parameters, so I would be able to call it like this:

dfuMaker.py --bin {file} {address}

Where address can have a default value if not passed.

Currently, this is how I'm defining the argument.

cmdParser.add_argument(
    '--bin', action='store', nargs=2, required=True)

And of course when trying to pass just 1 argument it fails with the error:

DFUMaker: error: argument --bin: expected 2 arguments

Upvotes: 0

Views: 348

Answers (1)

chepner
chepner

Reputation: 532268

I would use a custom type.

def file_address_pair(s):
    x = s.split(",", 1)
    if len(x) == 1:
        x.append(DEFAULT_ADDRESS)
    return x


p.add_argument("--bin", type=file_address_pair)

Despite the name, the type argument can be any callable that takes a str and returns a value; it doesn't have to be an actual Python type.

Then you can use either of

dfuMaker.py --bin f
dfuMaker.py --bin f,addr

Upvotes: 1

Related Questions