Python argparse: Force a list item to be unique

后端 未结 4 1706
广开言路
广开言路 2021-01-19 16:17

Being able to validate the list items using choices=servers below is nice.

servers = [ \"ApaServer\", \"BananServer\", \"GulServer\", \"SolServ         


        
4条回答
  •  醉话见心
    2021-01-19 17:04

    The way to properly discard duplicates using argparse would be to create your own argparse.Action class that takes care of using set as suggestted by other answers:

    import argparse
    
    class UniqueAppendAction(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            unique_values = set(values)
            setattr(namespace, self.dest, unique_values)
    
    servers = ["ApaServer", "BananServer", "GulServer", "SolServer",
               "RymdServer", "SkeppServer", "HavsServer", "SovServer" ]
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--only', nargs='*', choices=servers, action=UniqueAppendAction,
                        help='Space separated list of case sensitive server names to process')
    print parser.parse_args()
    

    Example output:

    $ python test.py -o ApaServer ApaServer
    Namespace(only=set(['ApaServer']))
    

提交回复
热议问题