简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM