So using argparse I created a mutually exclusive group which has two items. One of the must be always passed, so I created the group with required=True
.
It's properly working, If I don't call the script with either of them, it will fail with error: one of the arguments --foo --bar is required
However, the problem comes when I just run it with -h
or --help
. It's listing these parameters as optional, but they are not.
optional arguments:
-h, --help show this help message and exit
--foo foo
--bar bar
required arguments:
--alice alice
Is there any solution to list them as required? As add_mutually_exclusive_group()
does not support the title
parameter, I cannot do something like add_mutually_exclusive_group('must pick one', required=True)
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
required is a parameter of the ArugmentParser object's function add_argument() . By default, the arguments of type -f or --foo are optional and can be omitted. If a user is required to make an argument, they can set the keyword argument required to True .
action defines how to handle command-line arguments: store it as a constant, append into a list, store a boolean value etc. There are several built-in actions available, plus it's easy to write a custom one.
This is an open issue in python's issue tracker, however there is a simple workaround for it.
Simply create a titled group and add your mutually exclusive group to that one:
parser = argparse.ArgumentParser()
g1 = parser.add_argument_group(title='Foo Bar Group', description='One of these options must be chosen.')
g2 = g1.add_mutually_exclusive_group(required=True)
g2.add_argument('--foo',help='Foo help')
g2.add_argument('--bar',help='Bar help')
Courtesy of Paul.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With