是否可以仅使用 argparse 解析一个参数组的参数? [英] Is it possible to only parse one argument group's parameters with argparse?

查看:35
本文介绍了是否可以仅使用 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()

但是,我收到以下错误:

However, I'm getting the following error:

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,但只影响 helpusage 部分,并通过引发错误消息影响解析.

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 机制,它允许您将一个 parser insert 插入到另一个中.或者 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屋!

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