I have a mutually exclusive group where the user can choose from --execute, --delete, --create
. How can I make arguments only available for specific groups? For example --execute {filename}
, --create -fn {filename} -p {path}
and --delete {filename}
. How can I group up the optional arguments so they only can be used in a specific group?
Asked
Active
Viewed 39 times
1

Nicke7117
- 187
- 1
- 10
-
Take a look at [sub parsers](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_subparsers) – Wombatz Sep 03 '21 at 14:27
-
Sure, but how would I implement it with `add_mutually_exclusive_group`, there's not an example? @Wombatz – Nicke7117 Sep 03 '21 at 14:31
-
The commands from sub parsers are already mutually exclusive. You don't need that function. – Wombatz Sep 03 '21 at 14:34
-
Okay! But it's not then possible to use `-e`? Writing `execute` takes time and is a bit annoying.... @Wombatz – Nicke7117 Sep 03 '21 at 14:39
-
Mutually exclusive groups are flat - xor. They don't implement any sort of any/all subgroups. – hpaulj Sep 03 '21 at 15:18
1 Answers
1
The three "options" --execute
, --delete
and --create
look like they should be sub-commands and not optional flags.
For this, use the ArgumentParser.add_subparsers()
from argparse import ArgumentParser
parser = ArgumentParser()
sub = parser.add_subparsers()
execute = sub.add_parser('execute')
execute.add_argument('filename')
create = sub.add_parser('create')
create.add_argument('-fn')
create.add_argument('-p')
The usage is then
program execute {filename}
program create -fn {filename} -p {path}
You can even create an alias for the sub parsers:
sub.add_parser('execute', aliases=['e'])
This also allows you to call the program like this:
program e {filename}
Note:
It is not possible to use --execute
or -e
as the command for a sub parser, because when typing program --execute {filename}
the --execute
part is interpreted as a flag for the root parser and not as a sub command.

Wombatz
- 4,958
- 1
- 26
- 35