Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a solution for required mutually exclusive arguments listed as optional in help section?

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)

like image 664
Ay0 Avatar asked Nov 27 '18 11:11

Ay0


People also ask

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do you make an argument compulsory in Python?

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 .

What is action in Argparse?

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.


1 Answers

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.

like image 170
mehdix Avatar answered Sep 24 '22 04:09

mehdix