Argparse:如何为一个子命令声明多个互斥的参数组?如何定义多种使用子命令的方式?

2024-04-20 14:52:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要实现一个命令行,其中有几种使用子命令的方法。你知道吗

示例:

对于这个简单的“git合并”,有两种相互排斥的使用方法。你知道吗

1) git merge (--continue | --abort | --quit)
2) git merge [--no-commit] [-m <msg>] [<commit>​]

我的问题是:

使用argparse,如何实现这个简单示例的解析器?你知道吗

我用过:

  • “add\u subparsers”创建merge子命令。你知道吗
  • “add|mutual|u exclusive|u group”表示“(—continue |—abort |—quit)”。你知道吗
  • “add\u argument\u group”以重新发送第二种使用方法。你知道吗

这是我的密码:

# Template command
parser_template = subparsers.add_parser('merge')

groupA = parser_template.add_argument_group('When merge is on-going')
excl_group = groupA.add_mutually_exclusive_group(required=True)
excl_group.add_argument('--continue', action='store_true')
excl_group.add_argument('--abort', action='store_true')
excl_group.add_argument('--quit', action='store_true')

groupB = parser_template.add_argument_group('Start a merge')
groupB.add_argument('--no-commit', action='store_true')
groupB.add_argument('-m', metavar='<msg>')
groupB.add_argument('commit', metavar='<commit>')

帮助信息是:

(venv) >> git merge -h
usage: git merge [-h] [--no-commit] [-m <msg>]
                 (--continue | --abort | --quit)
                 <commit>

optional arguments:
  -h, --help   show this help message and exit

When merge is on-going:
  --continue
  --abort
  --quit

Start a merge:
  --no-commit
  -m <msg>
  <commit>

然而,groupA和groupB之间并不是相互排斥的。我们可以从“用法”部分看到,这个命令在没有意义的情况下工作:

(venv) >> git merge --no-commit --continue 34567

A组和B组如何相互排斥?你知道吗

最后,如果argparse不可用,是否存在具有此功能的其他库?你知道吗

谢谢你的帮助。你知道吗


Tags: nogitaddparsergroupactionmsgmerge