Search code examples
pythonargparsesubparsers

Display subgroups of commands with argparse subparser


I am currently developing a program in Python that contains ~40 sub commands. The parser is done using argparse. As the number of sub commands increases it is becoming complicated to search for the command of interest. Currently, it appears as below.

$ pgrm -h
  Usage: pgrm [-h] [-v]  ...

  Blabla bla.

Main command arguments:
 -h, --help          show this help message and exit
 -v, --version       show program's version number and exit

Available sub-commands:

  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…


Usage example:
 'pgrm sub-command -h' for more information.

I would like to change the display in order to show categories (e.g updating/inserting/selecting) and associated subcommands.

$ pgrm -h
  Usage: pgrm [-h] [-v]  ...

  Blabla bla.

Main command arguments:
 -h, --help          show this help message and exit
 -v, --version       show program's version number and exit

Available sub-commands:

Updating
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
Selecting
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
Inserting
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…
  sub_cmd        Some description about the command…  

Is there any solution that can be used in argparser to implement such CLI ?

Thank you


Solution

  • I explored this issue several years ago

    http://bugs.python.org/issue9341 allow argparse subcommands to be grouped

    If I read my proposed patch correctly, it just requires changing the _SubParsersAction class, and no further changes to the HelpFormatter or ArgumentParser classes.