add_argument
创建一个Action
对象,用于编码add_argument
调用中给出的参数。这些参数可以在创建后进行读取和/或修改。
class BaseClass(object)
def __init__(self):
self.parser = argparse.ArgumentParser()
self.arg = self.parser.add_argument("arg1", choices=("a", "b"))
class DerivedClass(BaseClass):
def __init__(self):
BaseClass.__init__(self)
self.arg.choices = ("a","b","c")
那个 Action 对象也可以在 parser._actions
列表中找到,但我更喜欢在我的代码中保存一个引用。
(这段代码没有经过测试,可能会有一两个错误。)
class BaseClass(object):
def __init__(self):
self.parser = argparse.ArgumentParser(prog="BASE")
self.parser.add_argument("arg1", choices=("a", "b"))
self.parser.add_argument('-f','--foo')
class DerivedClass(BaseClass):
def __init__(self):
BaseClass.__init__(self)
self.parser.prog = "DERIVED"
print(self.parser._actions)
在创建DerivedClass时,显示此列表:
。
[_HelpAction(option_strings=['-h', '--help'], dest='help', nargs=0, const=None, default='==SUPPRESS==', type=None, choices=None, help='show this help message and exit', metavar=None),
_StoreAction(option_strings=[], dest='arg1', nargs=None, const=None, default=None, type=None, choices=('a', 'b'), help=None, metavar=None),
_StoreAction(option_strings=['-f', '--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)]
"所以添加:"
idx = [a.dest for a in self.parser._actions].index('arg1')
self.parser._actions[idx].choices = ("a","b","c")
p1 = BaseClass()
p1.parser.print_help()
p2 = DerivedClass()
p2.parser.print_help()
产生两种用途:
usage: BASE [-h] [-f FOO] {a,b}
positional arguments:
{a,b}
optional arguments:
-h, --help show this help message and exit
-f FOO, --foo FOO
并且
usage: DERIVED [-h] [-f FOO] {a,b,c}
positional arguments:
{a,b,c}
optional arguments:
-h, --help show this help message and exit
-f FOO, --foo FOO
$ python subclass.py c 用法:subclass.py [-h] {a,b} {a,b,c} subclass.py:错误:参数arg1:无效的选择:'c'(可从'a'、'b'中选择)
- anthony sottile