是否可以仅使用argparse解析一个参数组的参数? [英] Is it possible to only parse one argument group's parameters with argparse?
问题描述
我正在做这样的事情:
parser = argparse.ArgumentParser()
group1 = parser.add_argument_group('group1')
group1.add_argument('--test1', help="test1")
group2 = parser.add_argument_group('group2')
group2.add_argument('--test2', help="test2")
group1_args = group1.parse_args()
group2_args = group2.parse_args()
但是,出现以下错误:
Traceback (most recent call last):
File "test.py", line 19, in <module>
group1_args = group1.parse_args()
AttributeError: '_ArgumentGroup' object has no attribute 'parse_args'
有没有一种方法只能获取一个参数组的参数?
Is there a way to only get the arguments for one argument group?
推荐答案
如您的错误消息所示,ArgumentGroup不是解析器,特别是它没有parse_args
方法.
As your error message indicates, an ArgumentGroup is not a parser, specifically it doesn't have the parse_args
method.
ArgumentParser对象和ArgumentGroup对象共享一个基本的ArgumentContainer类,该类为它们提供诸如add_argument
的方法.但是ArgumentParser有很多其他代码. ArgumentGroup实际上只是格式化help
的一种帮助.它不会以任何方式影响解析.
ArgumentParser objects and ArgumentGroup objects share a base ArgumentContainer class that gives them methods like add_argument
. But an ArgumentParser has a lot of additional code. An ArgumentGroup is really just an aid in formatting the help
. It does not affect parsing in any way.
为了增加混乱,mutually_exclusive_group
是ArgumentGroup
的子类,但仅影响help
的usage
部分,并通过引发错误消息来影响解析.
To add confusion, a mutually_exclusive_group
subclasses ArgumentGroup
, but affects only the usage
part of the help
, and affects parsing by raising an error message.
如果您详细说明了为什么要这样做,我们可以提出一些可行的替代方法.例如,有一种parents
机制,可让您insert
一个parser
转换为另一个.或subparsers
通过命令"参数将解析控制传递给子解析器.
If you elaborate on why you want to do this, we could come up with some alternatives that might work. For example there is a parents
mechanism, that lets you insert
one parser
into another. Or subparsers
that pass parsing control to a subparsers via 'command' arguments.
https://docs.python.org/3/library/argparse. html#parents
在自己的parent
解析器中定义每个组,将使您既可以控制帮助显示又可以控制解析.父母的唯一问题是您必须在某种程度上使用help=False
来防止-h
选项的重复.
Defining each group in its own parent
parser, would let you control both the help display, and parsing. Only problem with parents is that you have to use help=False
at some level to prevent the duplication of the -h
option.
您可能还需要使用parse_known_args
,以便组"解析器不会抱怨它无法识别的参数.
You may also need to use parse_known_args
so the 'group' parser does not complain about arguments that it does not recognize.
这是一种显示所有args
条目的方法,该条目按参数组分组.我包括2个默认组,可选和位置.它确实利用了解析器的私有"属性.这样做会有一定的风险,但这并不是将来的补丁中可能会更改的事情.
Here's a way of displaying all the args
entries, grouped by argument group. I'm including the 2 default groups, optionals and positionals. It does make use of 'private' attributes of the parser. There's a bit of risk in doing so, but this isn't the kind of thing that is likely to be changed in future patches.
import argparse
parser = argparse.ArgumentParser()
group1 = parser.add_argument_group('group1')
group1.add_argument('--test1', help="test1")
group2 = parser.add_argument_group('group2')
group2.add_argument('--test2', help="test2")
args = parser.parse_args('--test1 one --test2 two'.split())
print([g.title for g in parser._action_groups]) # all group titles
print(group1._group_actions) # arguments/actions of `group1`
print([a.dest for a in group2._group_actions]) # actions for group2
for group in parser._action_groups:
group_dict={a.dest:getattr(args,a.dest,None) for a in group._group_actions}
print(group.title, argparse.Namespace(**group_dict))
生产
1513:~/mypy$ python stack31519997.py
['positional arguments', 'optional arguments', 'group1', 'group2']
[_StoreAction(option_strings=['--test1'], dest='test1', nargs=None, const=None, default=None, type=None, choices=None, help='test1', metavar=None)]
['test2']
('positional arguments', Namespace())
('optional arguments', Namespace(help=None))
('group1', Namespace(test1='one'))
('group2', Namespace(test2='two'))
如果更方便地使用词典版本vars(args)
. argparse.Namespace(**adict)
从字典重新创建名称空间.
If could be more convenient to work with vars(args)
, the dictionary version. argparse.Namespace(**adict)
recreates a namespace from a dictionary.
粗略地说,您要创建自己的dest
列表,['test1']
和['test2']
.
Of coarse you make your own dest
lists, ['test1']
and ['test2']
.
这篇关于是否可以仅使用argparse解析一个参数组的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!