TLDR: Is there a way to check if any arguments in an argument group have been used? Without checking each argument individually?
I'm trying to achieve something similar to this question: Python argparse mutual exclusive group,
Essentially, trying to find the cleanest way to implement mutually exclusive argument groups.
test.py [-a xxx | [-b yyy -c zzz]]
Expanding on the previous linked question, I tried the following code block on python 3.10.2
import argparse
parser = argparse.ArgumentParser()
group= parser.add_argument_group('Model 2')
group_ex = group.add_mutually_exclusive_group()
group_ex.add_argument("-z", type=str, action = "store", default = "", help="test")
group_ex_1 = group_ex.add_argument_group("option 1")
group_ex.add_argument("-a", type=str, action = "store", default = "", help="test")
group_ex_2 = group_ex.add_argument_group("option 2")
group_ex_2.add_argument("-b", type=str, action = "store", default = "", help="test")
group_ex_2.add_argument("-c", type=str, action = "store", default = "", help="test")
args = parser.parse_args()
My goal was to be able to use group_ex_1
or group_ex_2
, but not both, but that seems to not be possible and results in this. Note that argument groups "option 1" and "option 2" do not even appear in the --help
output, but the options themselves do.
./test.py --help
usage: test.py [-h] [-z Z] [-a A] [-b B] [-c C]
options:
-h, --help show this help message and exit
Model 2:
-z Z test
Without adding an argument to group_ex
, I receive this error.
File "/usr/lib64/python3.10/argparse.py", line 396, in _format_actions_usage
raise ValueError(f'empty group {group}')
ValueError: empty group <argparse._MutuallyExclusiveGroup object at 0x7f804595a2c0>
Seems reasonable to have mutually exclusive groups of arguments, but appears to not be possible. So I'm looking for an alternative.