Logan Logan - 3 months ago 36
Python Question

Reorder Python argparse argument groups

I'm using

argparse
and I have a custom argument group
required named 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 named arguments:
-i INPUT, --input INPUT
Input file name


to this:

usage: foo.py [-h] -i INPUT [-o OUTPUT]

Foo

required named 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)

Answer

You might consider adding an explicit optional arguments group:

import argparse

parser = argparse.ArgumentParser(description='Foo', add_help=False)

requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)

optional = parser.add_argument_group('optional arguments')
optional.add_argument("-h", "--help", action="help", help="show this help message and exit")
optional.add_argument('-o', '--output', help='Output file name', default='stdout')

parser.parse_args(['-h'])

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:

usage: code.py -i INPUT [-h] [-o OUTPUT]

Foo

required named 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