Ed Dunn
Ed Dunn

Reputation: 1172

Using argparse with a specified acceptable option

I am trying to use argparse to accept required command line options. I have defined a function like so

def get_args():
    parser = argparse.ArgumentParser(description='Help Desk Calendar Tool')
    parser.add_argument('-s', '--start', type=str, required=True, metavar='YYYY-MM-DD')
    parser.add_argument('-e','--end', type=str, required=True, metavar='YYYY-MM-DD')
    parser.add_argument('-m','--mode', type=str, required=True , metavar='add|del')
    args = parser.parse_args()

    start = args.start
    end = args.end
    mode = args.mode
    return start,end,mode

What I am trying to do is for the option --mode I would like it to ONLY accept an parameter of either add or del. I could do this from an if statement but was wondering if argparse has a built in way of accomplishing this task. I looked at nargs but wasn't too clear if that's the path I need to go down

Upvotes: 2

Views: 140

Answers (1)

alecxe
alecxe

Reputation: 474281

I think you are asking about choices:

parser.add_argument('-m','--mode', type=str, required=True, choices=['add', 'del'])

Demo:

$ python test.py -s 10 -e 20 -m invalid
usage: test.py [-h] -m {add,del}
test.py: error: argument -m/--mode: invalid choice: 'invalid' (choose from 'add', 'del')

Upvotes: 3

Related Questions