I'm using argparse
and I have a custom argument group required arguments
. Is there any way to change the order of the argument groups in the help message? I think it is more logical to have the required arguments before optional arguments, but haven't found any documentation or questions to help.
For example, changing this:
usage: foo.py [-h] -i INPUT [-o OUTPUT]
Foo
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file name
required arguments:
-i INPUT, --input INPUT
Input file name
to this:
usage: foo.py [-h] -i INPUT [-o OUTPUT]
Foo
required arguments:
-i INPUT, --input INPUT
Input file name
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file name
(example taken from this question)
You might consider adding an explicit optional arguments group:
You can move the help action to your optional group as described here: Move "help" to a different Argument Group in python argparse
As you can see, the code produces the required output:
The parser starts out with 2 argument groups, the usual
positional
andoptionals
. The-h
help is added tooptionals
. When you doadd_argument_group
, a group is created (and returned to you). It is also appended to theparser._action_groups
list.When you ask for help (
-h
)parser.format_help()
is called (you can do that as well in testing). Look for that method inargparse.py
. That sets up the help message, and one step is:So if we reorder the items in the
parser._action_groups
list, we will reorder the groups in the display. Since this is the only use of_action_groups
it should be safe and easy. But some people aren't allowed to peak under the covers (look or change._
attributes).The proposed solution(s) is to make your own groups in the order you want to see them, and make sure that the default groups are empty (the
add_help=False
parameter). That's the only way to do this if you stick with the public API.Demo:
Run result:
_actions_group
list and titles:default help:
after reverse:
Another way to implement this is to define a
ArgumentParser
subclass with a newformat_help
method. In that method reorder the list used in thatfor action_group...
loop.This is admittedly a hack, and is reliant on the changeable internal implementation, but after adding the arguments, you can simply do:
This will effectively make the required arguments group display above the optional arguments group. Note that this answer is only meant to be descriptive, not prescriptive.
Credit: answer by hpaulj