Hello:
I’m trying to use the argparse
module to provide the argument parsing.
In my use case, I have eight positional arguments: arg1
, arg2
, arg3
, arg4
, arg5
, arg6
, arg7
, arg8
:
-
arg1
andarg2
are required. -
arg3
andarg4
are a couple and optional. But if users pass in one(arg3
orarg4
), they must pass in the other at the same time. -
arg5
andarg6
are another couple and same witharg3
andarg4
. -
arg7
andarg8
are another couple and same witharg5
andarg6
. But they are mutually exclusive with the grouparg5
andarg6
So my code is:
parser = argparse.ArgumentParser(description='Test.')
parser.add_argument('--arg1', type=str, required=True)
parser.add_argument('--arg2', type=str, required=True)
group1 = parser.add_argument_group(title='Group of arg3 and arg4')
group1.add_argument('--arg3', required=True)
group1.add_argument('--arg4', required=True)
group2 = parser.add_argument_group(title='Group of arg5 and arg6') # group2 is not mutually exclusive with group1
group2.add_argument('--arg5', required=True)
group2.add_argument('--arg6', required=True)
group3 = parser.add_argument_group(title='Group of arg7 and arg8') # group3 is mutually exclusive with group2
group3.add_argument('--arg7', required=True)
group3.add_argument('--arg8', required=True)
Three groups are optional which means users could just pass in --arg1 xx --arg2 xx
.
But the use case: --arg1 xx --arg2 xx --arg3 xx
is not allowed
I know the add_argument_group()
is just used for the help message.
Is there any way to implement the example using the argparse
itself instead of adding additional if-else
logic?