我的脚本定义了一个主解析器和多个子解析器.我想将这个-p论点应用于一些subparser.到目前为止代码看起来像这样:
parser = argparse.ArgumentParser(prog="myProg")
subparsers = parser.add_subparsers(title="actions")
parser.add_argument("-v", "--verbose",
action="store_true",
dest="VERBOSE",
help="run in verbose mode")
parser_create = subparsers.add_parser ("create",
help = "create the orbix environment")
parser_create.add_argument ("-p",
type = int,
required = True,
help = "set db parameter")
# Update
parser_update = subparsers.add_parser ("update",
help = "update the orbix environment")
parser_update.add_argument ("-p",
type = int,
required = True,
help = "set db parameter")
Run Code Online (Sandbox Code Playgroud)
如你所见,add_arument ("-p")重复两次.我实际上有更多的subsparsers.有没有办法循环遍历现有的子分析符以避免重复?
为了记录,我使用的是Python 2.7
最近,我正在学习argparse模块,代码下面发生了Argument错误
import argparse
import sys
class ExecuteShell(object):
def create(self, args):
"""aaaaaaa"""
print('aaaaaaa')
return args
def list(self, args):
"""ccccccc"""
print('ccccccc')
return args
def delete(self, args):
"""ddddddd"""
print('ddddddd')
return args
class TestShell(object):
def get_base_parser(self):
parser = argparse.ArgumentParser()
parser.add_argument('-h',
'--help',
action='store_true',
help=argparse.SUPPRESS)
parser.add_argument('-c', action='store',
dest='create_value',
help='create a file')
parser.add_argument('-d', action='store',
dest='delete_value',
help='delete a file')
parser.add_argument('-l', action='store',
dest='list_value',
help='list a dir')
return parser
def _find_actions(self, subparsers, actions_module):
for attr in (action for action in dir(actions_module) if not action.startswith('__')):
callback = getattr(actions_module, attr)
desc = …Run Code Online (Sandbox Code Playgroud)