【问题标题】:argparse with argument_groups and mututally_exclusive_group带有 argument_groups 和 mututally_exclusive_group 的 argparse
【发布时间】:2015-04-17 10:57:51
【问题描述】:

我有以下几点:

def parser():
    p = argparse.ArgumentParser()
    people = p.add_argument_group('people_list')
    meg = people.add_mutually_exclusive_group()
    meg.add_argument('--config-file')
    g = meg.add_argument_group('people')
    g.add_argument('--name')
    g.add_argument('--age')
    return p

p = parser()

p.parse_args(['--config-file', 'cfg_file', '--name', 'Bob', '--age', '3'])

我希望这会因mutually_exclusive 组而抱怨。请注意,这是实际代码的 sn-p,我有几个需要使用的 argument_groups,但在此 argument_group('people_list') 中,我希望用户指定配置文件或任何其他参数.

所以,我的用户应该可以说

prog --config-file cfg_file

prog --name Bob --age 3

但不是

prog --config-file cfg_file --name Bob --age 3

我在这里做错了什么?

【问题讨论】:

  • 我希望它会抛出一个异常,因为 devices 在定义之前被引用和/或没有属性 add_mutually_exclusive_group...
  • @twalberg。类型,固定。应该是人

标签: python arguments command-line-arguments argparse


【解决方案1】:

这里是帮助:

usage: foo [-h] [--config-file CONFIG_FILE] [--name NAME]
                        [--age AGE]

optional arguments:
  -h, --help            show this help message and exit

people_list:
  --config-file CONFIG_FILE

people 这样的参数组控制帮助行的显示方式。因此,标题为 people_list 的部分。

互斥组控制用法的格式,并检查参数的共现。从技术上讲,它是参数组的子类,但是这两种组的交互并不多。

您可以在参数组中嵌套一个互斥组,就像您在此处所做的那样。但是您不能将参数组嵌套在另一个组(任何一种)中。或者更确切地说,它会接受这样的定义,但它并没有什么特别之处。因此nameage 已添加到解析器中(如使用中所见),但未添加到megpeople。而如果你将一个互斥的组添加到另一个 MXGroup,效果就是创建一个大的扁平组。

所以,除了一个小例外,不要试图将一个组嵌套在另一个组中。他们的定义还不够笼统,无法以这种方式做任何有用的事情。

如果您将nameage 添加到meg,那么帮助将是:

usage: foo [-h]
                        [--config-file CONFIG_FILE | --name NAME | --age AGE]

optional arguments:
  -h, --help            show this help message and exit

people_list:
  --config-file CONFIG_FILE
  --name NAME
  --age AGE

这将反对将config-filenameage 一起使用。但它也会反对同时使用nameage

存在要求通用嵌套相互 xxx 组的错误问题。一旦实现,它就可以处理这种通用逻辑。但就目前而言,它不能。假设您可以设置所需的测试,理想的使用线会是什么样子?设置测试相对容易,但要产生有意义的使用则要困难得多。

现在我建议你自己写usage。使用argument groups 对参数帮助行进行分组。解析后进行自己的交互测试。您可以使用p.error... 生成错误消息。如果您明智地选择默认值,那么测试参数并不难,例如

if args.config_file is not None and 
    (args.name is not None or args.age is not None): 
    p.error('...')

【讨论】:

    猜你喜欢
    • 2019-06-23
    • 2018-06-29
    • 2020-10-26
    • 2011-05-26
    • 2014-04-02
    • 2016-06-10
    • 2018-09-25
    • 2013-08-19
    • 2016-07-12
    相关资源
    最近更新 更多