使用 argparse 创建互斥参数

Create Mutual Inclusive arguments with argparse

我想构建一个程序,其中包含 2 个相互包含的参数和 2 个不依赖于前两个的参数。像这样:

consume [--count n] | show | clear

其中 'consume' 和 '--count' 相互依赖,即没有 'consume' '--count' 将引发错误 'show' 和 'clear'不依赖于第一次消费和 --count.

编辑: show 和 clear 是可选参数

这是我到目前为止能够做的事情:

import argparse
parser = argparse.ArgumentParser()
group = argparse.ArgumentParser(usage='%(prog)s [consume [--count]]')
group.add_argument('consume', help='mutually inclusive with count')
group.add_argument('--count', type = int, help='get the count n')

parser.add_argument('show', help='show the messages')
parser.add_argument('clear', help='clear messages from db')

args = group.parse_args()
args1 = parser.parse_args()

if args.count and not args.consume:
    parser.error('the following arguments are required: consume')
else:
    print(args.count)
    print(args1.show)
    print(args1.clear)

所以当运行命令时,没有消耗:

[filename] --count 7 show clear

我收到以下错误:

unrecognized arguments: clear

有人可以帮助我使论点相互包容并使其他论点不依赖于它们吗?

你可以试试这样的……

添加一个MutuallyInclusiveArgumentErrorException子类,然后将参数拆分成一个参数组,解析完成后检查错误。

import argparse
import sys
class MutuallyInclusiveArgumentError(Exception):
    pass

parser = argparse.ArgumentParser(sys.argv[0])
subs = parser.add_argument_group("mutually inclusive")
subs.add_argument('--consume', help='mutually inclusive with count', action='store_true')
subs.add_argument('--count', type = int, help='get the count n')
parser.add_argument('--show', help='show the messages', action='store_true')
parser.add_argument('--clear', help='clear messages from db', action='store_true')


args = parser.parse_args()
if args.count and args.consume is False:
    raise MutuallyInclusiveArgumentError("--count option must be used with the --consume option" )



print(vars(args))

帮助消息如下所示

usage: {progname} [-h] [--consume] [--count COUNT] [--show] [--clear]

options:
  -h, --help     show this help message and exit
  --show         show the messages
  --clear        clear messages from db

mutually inclusive:
  --consume      mutually inclusive with count
  --count COUNT  get the count n