在查阅了上述内容并尝试了不同的方法后,我编写了这个示例。这是一个实现“Uncount”计数的类,它与“count”操作相反。
import argparse
class Uncount(argparse.Action):
def __init__(self, option_strings, dest, nargs=0, choices=None, const=None, **kwargs):
if nargs != 0:
raise ValueError("no arguments to this parameter are allowed")
if const is not None:
raise ValueError("this parameter does not permit constants")
if choices is not None:
raise ValueError("no choices to this parameter are allowed")
super(Uncount, self).__init__(option_strings=option_strings, nargs=nargs, dest=dest,**kwargs)
def __call__(self, parser, namespace, values, option_string=None):
value = getattr(namespace, self.dest, 0)
setattr(namespace, self.dest, value-1)
opts={}
argparser = argparse.ArgumentParser(description='Report on other teams')
argparser.add_argument(
'-v','--verbose',dest='verbose',default=0,action='count',
help='increase log level',
)
argparser.add_argument(
'-q','--quiet',dest='verbose',default=0,action=Uncount,
help='increase log level',
)
例子:
>>> argparser.parse_args('-q -q'.split())
Namespace(verbose=-2)
>>> argparser.parse_args('-q -v'.split())
Namespace(verbose=0)
>>> argparser.parse_args('-q -v -v'.split())
Namespace(verbose=1)