Python argparse: Mutually exclusive required group with a required option -
i trying have required mutually exclusive group 1 required parameter. below code have put
#!/usr/bin/python import argparse import sys # check option provided part of arguments def parseargv(): parser = argparse.argumentparser() group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", choices=[1,2,3,4], = "increase verbosity") group.add_argument("-q", "--quiet", action="store_true", = "run quietly") name = parser.add_mutually_exclusive_group(required=true) name.add_argument("-n", "--name", = "name of virtual machine") name.add_argument("-t", "--template", = "name of template use \ creating vm. if path not provided looked \ under template directory.") parser.add_argument("-s", "--save", = "save machine template. if \ path not provided saved under template directory."); #parser.add_argument("-k", "--kick_start", required = true, = "name of \ # kick start file. if path not provided http \ # directory.") if len(sys.argv) == 1: parser.print_help() args = parser.parse_args() if __name__ == '__main__': parseargv()
now output of program follow
$ python test.py usage: test.py [-h] [-v {1,2,3,4} | -q] (-n name | -t template) [-s save] optional arguments: -h, --help show message , exit -v {1,2,3,4}, --verbose {1,2,3,4} increase verbosity -q, --quiet run quietly -n name, --name name name of virtual machine -t template, --template template name of template use creating vm. if path not provided looked under template directory. -s save, --save save save machine template. if path not provided saved under template directory. usage: test.py [-h] [-v {1,2,3,4} | -q] (-n name | -t template) [-s save] test.py: error: 1 of arguments -n/--name -t/--template required
but if un-comment line 20 - 22 output change below
$ python test.py usage: test.py [-h] [-v {1,2,3,4} | -q] (-n name | -t template) [-s save] -k kick_start optional arguments: -h, --help show message , exit -v {1,2,3,4}, --verbose {1,2,3,4} increase verbosity -q, --quiet run quietly -n name, --name name name of virtual machine -t template, --template template name of template use creating vm. if path not provided looked under template directory. -s save, --save save save machine template. if path not provided saved under template directory. -k kick_start, --kick_start kick_start name of kick start file. if path not provided http directory. usage: test.py [-h] [-v {1,2,3,4} | -q] (-n name | -t template) [-s save] -k kick_start test.py: error: argument -k/--kick_start required
but want either -n / -t along -k become mandatory. how achieve same.
you have achieved it! argparse prints first error finds, while may it's checking -k, recuires -n/-t too. can see giving -k argument.
if provide -k argument, error message change test.py: error: argument -k/--kick_start required
test.py: error: 1 of arguments -n/--name -t/--template required
.
Comments
Post a Comment