使用argparse subparser显示命令的子组

时间:2017-05-31 18:15:29

标签: python argparse subparsers

我目前正在开发一个包含~40个子命令的Python程序。解析器使用argparse完成。随着子命令的数量增加,搜索感兴趣的命令变得复杂。目前,它显示如下。

$ 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.

我想更改显示以显示类别(例如更新/插入/选择)和相关的子命令。

$ 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…  

有没有可以在argparser中使用的解决方案来实现这样的CLI?

谢谢

1 个答案:

答案 0 :(得分:1)

我几年前探讨了这个问题

http://bugs.python.org/issue9341 允许对argparse子命令进行分组

如果我正确阅读了我提议的修补程序,只需要更改_SubParsersAction类,而不需要对HelpFormatterArgumentParser类进行进一步更改。