So I'm trying to parse the command line for 2 groups of mutually exclusive arguments.
I'm looking at the argparse.add_mutually_exclusive_group function. However, it doesn't seem like it will do what I need. I want to let someone specify a file or specify a jenkins server with a view. I don't know how to manipulate add_mutually_exclusive_group to either accept a 1 argument group or a 2 argument group. I will save everyone the pain of looking at my other failed trials but I'm getting the feeling either
Here's my code, although, I know it's wrong because I'm not using it correctly to make jenkins and view be a group but I don't know what to do to accomplish that.
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--file', dest='file', help='Get jobs from file')
group.add_argument('--jenkins', dest='jenkins', help='Get jobs from Jenkins view and separate by section')
group.add_argument('--view', dest='view')
Your code is very close to what it needs to be, you're specification for mutually exclusive should look more like this, and also have a catch to require --view
only when using --jenkins
:
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--file', dest='file')
group.add_argument('--jenkins', dest='jenkins')
parser.add_argument('--view', dest='view')
args = parser.parse_args()
if args.jenkins and not args.view:
parser.error("--view is required when using --jenkins")
EDIT: After posting I noticed a slightly cleaner (but not necessarily better) way to do this after looking at the docs, but it would require you to process the command slightly differently:
group.add_argument('--jenkins', dest='jenkins', nargs=2, metavar=('JENKINS', 'VIEW'))
This will send the array ['ABC', 'XYZ']
to the jenkins
destination
metavar
changes how the name is displayed in help, so it'll show:
usage: test_parse.py [-h] (--file FILE | --jenkins JENKINS VIEW)
test_parse.py: error: argument --jenkins: expected 2 arguments
nargs=2
implies that the argument must be used twice, requiring the user to input --jenkins ABC XYZ
instead of --jenkins ABC --view XYZ