kelua
kelua

Reputation: 283

Optional keyword arguments - argparse

I'm trying to make a program where there are 3 different options for keyword arguments input(the user must choose one of them):

1) The first one is when the user enters two integers so the program will be called like this :

python myProgram.py -s 3 -p 9

2) The second one is when the user enters a string of ones and zeros :

python myProgram.py -r 1101011010

3) The third input is the same as the second one, but it is stored in a different variable

python myProgram.py -l 1101011010

How can I implement this? I have read about argparse and nargs = '?' but I got confused and I don't know how to do this.

Upvotes: 0

Views: 825

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122032

You could use mutual exclusion to create your 3 options (and mark the group as required). You'll have to manually test if -s is used if -p is present, however:

parser = argparse.ArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-s', type=int)
parser.add_argument('-p', type=int)

def binary(value):
    # just test if the value is a valid binary string
    try:
        int(value, 2)
    except ValueError:
        raise argparse.ArgumentTypeError('{!r} is not a valid binary value'.format(value))
    return value

group.add_argument('-r', type=binary)

group.add_argument('-l', type=binary)

args = parser.parse_args()
if args.s and args.p is None:
    parser.error('You must use -p when -s is selected')

Upvotes: 1

Related Questions