Python - argparse require either or -


when run script, have pass either -g or -s. code below, throws following error argument(s) passed it.

{~/nsnitro}-> ./sg-arg.py status -g test.server usage: sg-arg.py [-h] (-g servicegroup | -s servicename) {status} ... sg-arg.py: error: 1 of arguments -g/--servicegroup -s/--servicename required 

code:

parser = argparse.argumentparser() subparsers = parser.add_subparsers()  check = subparsers.add_parser('status') check = parser.add_mutually_exclusive_group(required=true) check.add_argument('-g', '--servicegroup', action='store', help='servicegroup name', type=servicegroup_status) check.add_argument('-s', '--servicename', action='store', help='service name', type=servicegroup_status)  args = parser.parse_args() 

you're adding mutually exclusive group wrong parser. in other words, call have, correct call ./sg-arg.py -g test.server status (notice argument comes before subparser declaration).

to fix it, you'd add mutual exclusion group subparser , add arguments group. seems work:

import argparse parser = argparse.argumentparser() subparsers = parser.add_subparsers()  check = subparsers.add_parser('status') check_mutex = check.add_mutually_exclusive_group(required=true) check_mutex.add_argument('-g', '--servicegroup', action='store', help='servicegroup name') check_mutex.add_argument('-s', '--servicename', action='store', help='service name')  args = parser.parse_args() 

e.g.

$ python foo.py status -g test.server $ python foo.py status -s test.server $ python foo.py status  test.server usage: foo.py status [-h] (-g servicegroup | -s servicename) foo.py status: error: 1 of arguments -g/--servicegroup -s/--servicename required 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -