python argparse:子解析器上的前缀或智能匹配

python argparse: prefix or smart matching on sub parsers

是否可以在 python 的 (2.7) argparse 中添加子解析器,在指定要执行的子命令时不需要完全匹配?有谁知道如何做到这一点?它已经对长选项进行了前缀匹配,例如--my-long-option 可以指定为 --my-l,只要它是所有其他选项中的唯一前缀即可。

例如,我想要一个像这样的命令 foo apple foo banana foo carrot

我可以指定 foo ap 来使用 foo apple 子解析器。

如果我使用记录的方案添加这些子解析器,这将不起作用,即

sub = parser.add_subparsers(help='commands')
apple = sub.add_parser( 'apple', ... )
banana = sub.add_parser( 'banana', ... )
carrot = sub.add_parser( 'carrot', ... )

这需要指定完整的子命令名称。

如您所见,长选项与缩写一起使用。在最近的版本中,您可以使用 allow_abbrev=False 参数将其关闭。

子解析器名称使用不同的机制处理。对于主解析器,add_subparsers(...) 创建一个位置操作,带有 choices 参数。

你的 subparsers 命令大致相当于:

sp = parser.add_argument(dest='cmd', choices={'apple','banana', 'carrot'}, action=argparse._SubParsersAction, nargs='+...')

正是 action 子类产生了独特的子解析器行为。

与常规 choices 一样,测试是

astring in choices

要求完全匹配,没有任何特殊缩写处理。

add_parser中的'aliases'参数可用于近似缩写。来自文档:

Furthermore, add_parser supports an additional aliases argument, which allows multiple strings to refer to the same subparser. This example, like svn, aliases co as a shorthand for checkout:

前段时间提出了一个允许缩写的补丁。它是去年提交的,但后来因为有一些错误而撤回了。

http://bugs.python.org/issue12713

I [hpaulj] recommend closing this issue, and depend on aliases for subparsers abbreviations. The interaction with 'choices' is just too complicated to handle as proposed here.