使用argparse子解析器显示命令的子组。

3

我正在使用Python开发一个包含约40个子命令的程序。解析器是使用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个回答

1
我几年前探索过这个问题。 http://bugs.python.org/issue9341 允许 argparse 子命令分组。
如果我正确地阅读了我的建议补丁,它只需要更改 _SubParsersAction 类,而不需要进一步更改 HelpFormatter 或 ArgumentParser 类。

非常感谢您,hpaulj。我会尽快查看。 - dputhier
运行得非常好。非常感谢你的帮助。 - dputhier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接