从外部模块添加 argparse 参数 [英] Add argparse arguments from external modules

查看:27
本文介绍了从外部模块添加 argparse 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a Python program that could be extended by third parties. The program will be run from the command line with whatever arguments are supplied.

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

In order to allow third parties to create their own modules, I've created the following (simplified) base class:

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

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

Any arguments that they supply via get_args() will be added to a subparser for that particular module. I want them to be able to specify any type of argument.

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

I'm not sure of the best way to declare and then get the arguments from the subclassed modules into my main program. I successfully find all subclasses of MyBaseClass and loop through them to create the subparsers, but I cannot find a clean way to add the individual arguments to the subparser.

这是主程序的当前代码:

Here is the current code from the main program:

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(...)

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

How can I best specify the arguments in the external modules via get_args() or similar and then add them to the subparser? One of my failed attempts looked like the following, which doesn't work because it tries to pass every possible option to add_argument() whether it has a value or is 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'],
                )

推荐答案

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

Without trying to fully understand your module structure, I think you want to be able to provide the arguments to a add_argument call as objects that you can import.

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

You could, for example, provide a list of positional arguments, and dictionary of keyword arguments:

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

parser=argparse.ArgumentParser()
parser.add_argument(*args, **kwargs)
parser.print_help()

生产

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

argparse.py中,add_argument方法(属于ArgumentParser的超类),有这个通用签名

In argparse.py, the add_argument method (of a super class of ArgumentParser), has this general signature

def add_argument(self, *args, **kwargs):

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

The code of this method manipulates these arguments, adds the args to the kwargs, adds default values, and eventually passes kwargs to the appropriate Action class, returning the new action. (It also 'registers' the action with the parser or subparser). It's the __init__ of the Action subclasses that lists the arguments and their default values.

这篇关于从外部模块添加 argparse 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆