Being able to validate the list items using choices=servers
below is nice.
servers = [ "ApaServer", "BananServer", "GulServer", "SolServer", "RymdServer", "SkeppServer", "HavsServer", "SovServer" ]
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--only', nargs='*', choices=servers, help='Space separated list of case sensitive server names to process')
Is it possible to force an item in the list to be unique, so that no duplicates are allowed?
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']))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With