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"))
# self.arg is now the Action object defined by this add_argument method
class DerivedClass(BaseClass):
def __init__(self):
BaseClass.__init__(self)
# modify the choices attribute of self.arg
self.arg.choices = ("a","b","c")
的行動目標,也可在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()
產生2個usag ES:
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
這段代碼有什麼問題?這個對我有用。你的論點被覆蓋。 – MrE
@MrE'''$ python subclass.py c 用法:subclass.py [-h] {a,b} {a,b,c} subclass.py:error:argument arg1:invalid choice:'c' (從'a','b'中選擇) ''' –
此代碼定義了2個位置參數,每個參數都有不同的選項集。 – hpaulj