argparse - disable same argument occurrences

后端 未结 2 1226
生来不讨喜
生来不讨喜 2020-12-11 05:25

I\'m trying to disable same argument occurences within one command line, using argparse

./python3 --argument1=something --argument2 --argument1=something_els         


        
2条回答
  •  离开以前
    2020-12-11 06:13

    I don't think there is a native way to do it using argparse, but fortunately, argparse offers methods to report custom errors. The most elegant way is probably to define a custom action that checks for duplicates (and exits if there are).

    class UniqueStore(argparse.Action):
        def __call__(self, parser, namespace, values, option_string):
            if getattr(namespace, self.dest, self.default) is not self.default:
                parser.error(option_string + " appears several times.")
            setattr(namespace, self.dest, values)
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--foo', action=UniqueStore)
    
    args = parser.parse_args()
    

    (Read the docs about cutom actions)

    Another way is to use the append action and count the len of the list.

    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--foo', action='append')
    args = parser.parse_args()
    
    if len(args.foo) > 1:
        parser.error("--foo appears several times.")
    

提交回复
热议问题