从外部模块添加argparse参数 [英] Add argparse arguments from external modules
问题描述
我正在尝试编写可由第三方扩展的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屋!