从外部模块添加argparse参数

doz*_*oza 6 python argparse

我正在尝试编写一个可以由第三方扩展的Python程序.程序将从命令行运行,提供任何参数.

为了允许第三方创建自己的模块,我创建了以下(简化)基类:

class MyBaseClass(object):
    def __init__(self):
        self.description = ''
        self.command = ''

    def get_args(self):
        # code that I can't figure out to specify argparse arguments here
        # args = []
        # arg.append(.....)
        return args
Run Code Online (Sandbox Code Playgroud)

他们通过get_args()提供的任何参数都将添加到该特定模块的subparser中.我希望他们能够指定任何类型的参数.

我不确定声明的最佳方法,然后从子类模块中获取参数到我的主程序中.我成功找到MyBaseClass的所有子类并循环遍历它们以创建子分析器,但我找不到一种干净的方法来将各个参数添加到subparser.

以下是主程序的当前代码:

for module in find_modules():
    m = module()
    subparser_dict[module.__name__] = subparsers.add_parser(m.command, help=m.help)
    for arg in m.get_args():
            subparser_dict[module.__name__].add_argument(...)
Run Code Online (Sandbox Code Playgroud)

如何通过get_args()或类似方法最好地指定外部模块中的参数,然后将它们添加到subparser?我失败的尝试之一看起来像以下一样,它不起作用,因为它试图将每个可能的选项传递给add_argument(),无论它是否有值或是None:

            subparser_dict[module.__name__].add_argument(arg['long-arg'],
                action=arg['action'],
                nargs=arg['nargs'],
                const=arg['const'],
                default=arg['default'],
                type=arg['type'],
                choices=arg['choices'],
                required=arg['required'],
                help=arg['help'],
                metavar=arg['metavar'],
                dest=arg['dest'],
                )
Run Code Online (Sandbox Code Playgroud)

hpa*_*ulj 4

在不尝试完全理解模块结构的情况下,我认为您希望能够将参数add_argument作为可以导入的对象提供给调用。

例如,您可以提供位置参数列表和关键字参数字典:

args=['-f','--foo']
kwargs={'type':int, 'nargs':'*', 'help':'this is a help line'}

parser=argparse.ArgumentParser()
parser.add_argument(*args, **kwargs)
parser.print_help()
Run Code Online (Sandbox Code Playgroud)

生产

usage: ipython [-h] [-f [FOO [FOO ...]]]

optional arguments:
  -h, --help            show this help message and exit
  -f [FOO [FOO ...]], --foo [FOO [FOO ...]]
                        this is a help line
Run Code Online (Sandbox Code Playgroud)

在 中argparse.pyadd_argument方法( 的超类ArgumentParser)具有以下通用签名

def add_argument(self, *args, **kwargs):
Run Code Online (Sandbox Code Playgroud)

此方法的代码操作这些参数,将 添加到argskwargs添加默认值,并最终传递kwargs到适当的Action类,返回新操作。(它还向解析器或子解析器“注册”操作)。Action 子类__init__列出了参数及其默认值。