I have a program that needs to have an option to either test a list of server ids OR issue a command against the server. This means, if I issue --test
, then nothing else is required. It runs the whole gamut of tests against each server and prints the results.
However, if I do NOT specify --test
, then it should require a few options such as --id
and --command
.
However, I'm not sure that argparse
can handle required options within mutually exclusive groups. Code (modified for simplicity) is as follows. I've modified the options so if you specify -a
, then you SHOULD be good to go and no other options be necessary.
import argparse
parser = argparse.ArgumentParser()
test_or_not = parser.add_mutually_exclusive_group(required=True)
test_or_not.add_argument('-a', action='store_true')
or_not = test_or_not.add_argument_group()
target = or_not.add_mutually_exclusive_group(required=True)
target.add_argument('-b',action="store_true")
target.add_argument('-c',action="store_true")
target.add_argument('-d',action="store_true")
target.add_argument('-e',action="store_true")
group = or_not.add_mutually_exclusive_group(required=True)
group.add_argument('-f',action="store_true")
group.add_argument('-g',action="store_true")
or_not.add_argument('-i',action="store_true")
or_not.add_argument('-j',action="store_true")
or_not.add_argument('-k',action="store_true")
or_not.add_argument('-l',action="store_true")
args = parser.parse_args()
The resulting error is produced because argparse
is still requiring individual options even though they're in a mutually exclusive group. Is there a way that argparse
can accommodate this set of options or do I need to add a bit of programming outside of argparse
?
$ python3 ~/tmp/groups.py -a
usage: groups.py [-h] -a (-b | -c | -d | -e) (-f | -g) [-i] [-j] [-k] [-l]
groups.py: error: one of the arguments -b -c -d -e is required
Edit: I could add a new option that entirely works OUTSIDE of argparse
as below, but I'd like to keep it structured within argparse
if at all possible.
import argparse
import sys
if '--test' in sys.argv:
go_do_testing()
sys.exit(0)
parser = argparse.ArgumentParser()
<snip>