Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse choices structure of allowed values

Using argparse in relation to Python dependencies between groups using argparse, I have an argument part of some parser group of a parser - for example:

group_simulate.add_argument('-P',
                            help='simulate FC port down',
                            nargs=1,
                            metavar='fc_port_name',
                            dest='simulate')

How it's possible to use the choices to limit the choices to a list of parameters of the next structure:

1:m:"number between 1 and 10":p:"number between 1 and 4"

I have tried to use the range option but I couldn't find a way to create a list of choices that are acceptable

examples: legal parameters:

test.py -P 1:m:4:p:2

not legal parameters:

test.py -P 1:p:2
test.py -P abvds

Thank you very much for the help guys!

like image 508
Elia Avatar asked Feb 02 '13 18:02

Elia


People also ask

How do you make an argument optional in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser.

What is action Store_true in Argparse?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.

What does DEST mean in Argparse?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object. dest identifies an argument.

Which of the following parameters is set to specify that passing an argument is mandatory while adding the argument to a created parser?

required is a parameter of the ArugmentParser object's function add_argument() . By default, the arguments of type -f or --foo are optional and can be omitted. If a user is required to make an argument, they can set the keyword argument required to True .


1 Answers

You can define a custom type that will raise an argparse.ArgumentTypeError if the string doesn't match the format you need.

def SpecialString(v):
    fields = v.split(":")
    # Raise a value error for any part of the string
    # that doesn't match your specification. Make as many
    # checks as you need. I've only included a couple here
    # as examples.
    if len(fields) != 5:
        raise argparse.ArgumentTypeError("String must have 5 fields")
    elif not (1 <= int(fields[2]) <= 10):
        raise argparse.ArgumentTypeError("Field 3 must be between 1 and 10, inclusive")
    else:
        # If all the checks pass, just return the string as is
        return v

group_simulate.add_argument('-P',
                        type=SpecialString,
                        help='simulate FC port down',
                        nargs=1,
                        metavar='fc_port_name',
                        dest='simulate')

UPDATE: here's a full custom type to check the value. All checking is done in the regular expression, although it only gives one generic error message if any part is wrong.

def SpecialString(v):
    import re  # Unless you've already imported re previously
    try:
        return re.match("^1:m:([1-9]|10):p:(1|2|3|4)$", v).group(0)
    except:
        raise argparse.ArgumentTypeError("String '%s' does not match required format"%(v,))
like image 166
chepner Avatar answered Oct 04 '22 14:10

chepner