52

How do I restrict the values of the argparse options?

In the below code sau option should only accept a number of 0 or 1 and bg should only allow an integer. How can I implement this?

import os
import sys, getopt
import argparse

def main ():
    parser = argparse.ArgumentParser(description='Test script')
    parser.add_argument('-sau','--set',action='store',dest='set',help='<Required> Set flag',required=True)
    parser.add_argument('-bg','--base_g',action='store',dest='base_g',help='<Required> Base g',required=True)
    results = parser.parse_args() # collect cmd line args
    set = results.set
    base_g = results.base_g

if __name__ == '__main__':
    main()
3
  • 1
    don't mask the builtin: set = results.set (you see the syntax highlighting colour)
    – eumiro
    Dec 28, 2012 at 9:51
  • Also, on a sidenote, if arguments are required, they shouldn't be flags but positional arguments. Dec 28, 2012 at 9:52
  • check this tutorial docs.python.org/howto/argparse
    – tshepang
    Dec 28, 2012 at 9:54

1 Answer 1

71

You can use the type= and choices= arguments of add_argument. To accept only '0' and '1', you'd do:

parser.add_argument(…, choices={"0", "1"})

And to accept only integer numbers, you'd do:

parser.add_argument(…, type=int)

Note that in choices, you have to give the options in the type you specified as the type argument. So to check for integers and allow only 0 and 1, you'd do:

parser.add_argument(…, type=int, choices={0, 1})

Example:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument("-p", type=int, choices={0, 1})
>>> parser.parse_args(["-p", "0"])
Namespace(p=0)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.