Restricting values of command line options

前端 未结 1 1700
借酒劲吻你
借酒劲吻你 2020-12-10 09:58

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 <

相关标签:
1条回答
  • 2020-12-10 10:34

    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 讨论(0)
提交回复
热议问题