指定一个参数以使其成为默认值

时间:2018-03-31 13:01:48

标签: python-3.x argparse

我在我的代码中有一个标志字典,作为argparser的新参数添加。它是在一个单独的词典中,因为我稍后需要帮助文本。

需要为parser.add_argument传递一些参数,但有时却不会。因此,如果它们不需要被传递,它们在dict中等于None。但是,如果我尝试传递None,它会认为这是一个新论点。如果代码等于None

,如何使代码不通过指定的参数
parser_arguments = {
    "--version" : {
        "alias" : "-V",
        "action" : "store_true",
        "help" : "Show Red's current version",
        "nargs" : None,
        "type" : None,
        "default" : None
    },
    "--list-instances" : {
        "alias" : None,
        "action" : "store_true",
        "help" : "List all instance names setup with 'redbot-setup'",
        "nargs" : None,
        "type" : None,
        "default" : None
    },
    "--owner" : {
        "alias" : None,
        "action" : "store_true",
        "help" : "ID of the owner. Only who hosts "
                "Red should be owner, this has "
                "serious security implications if misused.",
        "nargs" : None,
        "type" : None,
        "default" : None
    },
    "--co-owner" : {
        "alias" : None,
        "action" : "store_true",
        "help" : "ID of a co-owner. Only people who have access "
                "to the system that is hosting Red should be  "
                "co-owners, as this gives them complete access "
                "to the system's data. This has serious "
                "security implications if misused. Can be "
                "multiple.",
        "nargs" : "*",
        "type" : int,
        "default" : []
    },
    "--prefix" : {
        "alias" : "-p",
        "action" : "append",
        "help" : "Global prefix. Can be multiple",
        "nargs" : None,
        "type" : None,
        "default" : None
    }
}

parser = argparse.ArgumentParser(description="Red - Discord Bot",
                                 usage="redbot <instance_name> [arguments]")
for argument in parse_arguments:
    parser.add_argument(argument, argument["alias"], action=argument["action"], help=argument["help"], nargs=argument["nargs"], type=argument["type"], default=argument["default"]

我已经考虑过将dict中的参数作为默认参数,但未在API reference中指定

1 个答案:

答案 0 :(得分:0)

剥离None

的辅助函数
def foo(adic):
    newdic = {k:v for k,v in adic.items() if v is not None}
    try:
        alias = newdic.pop('alias')
    except KeyError:
        pass
    return newdic

e.g。 co-owner我在评论中注意到的更正

In [114]: foo(parser_arguments['--co-owner'])
Out[114]: 
{'default': [],
 'help': "ID of a co-owner. Only people who have access to the system that is hosting Red should be  co-owners, as this gives them complete access to the system's data. This has serious security implications if misused. Can be multiple.",
 'nargs': '*',
 'type': int}

In [115]: parser = argparse.ArgumentParser()
In [116]: for k, v in parser_arguments.items():
     ...:     args = [a for a in [v['alias']] if a is not None]
     ...:     parser.add_argument(k, *args, **foo(v))
     ...:   

In [117]: parser.print_help()
usage: ipython3 [-h] [--version] [--list-instances] [--owner]
                [--co-owner [CO_OWNER [CO_OWNER ...]]] [--prefix PREFIX]

optional arguments:
  -h, --help            show this help message and exit
  --version, -V         Show Red's current version
  --list-instances      List all instance names setup with 'redbot-setup'
  --owner               ID of the owner. Only who hosts Red should be owner,
                        this has serious security implications if misused.
  --co-owner [CO_OWNER [CO_OWNER ...]]
                        ID of a co-owner. Only people who have access to the
                        system that is hosting Red should be co-owners, as
                        this gives them complete access to the system's data.
                        This has serious security implications if misused. Can
                        be multiple.
  --prefix PREFIX, -p PREFIX
                        Global prefix. Can be multiple

add_argument返回刚刚创建的Action对象。可以查看甚至修改其某些属性。收集这些对象的列表可能很方便。或者您可以在创建后使用以下方式查看它们:

In [118]: parser._actions
Out[118]: 
[_HelpAction(option_strings=['-h', '--help'], dest='help', nargs=0, const=None, default='==SUPPRESS==', type=None, choices=None, help='show this help message and exit', metavar=None),
 _StoreTrueAction(option_strings=['--version', '-V'], dest='version', nargs=0, const=True, default=False, type=None, choices=None, help="Show Red's current version", metavar=None),
 _StoreTrueAction(option_strings=['--list-instances'], dest='list_instances', nargs=0, const=True, default=False, type=None, choices=None, help="List all instance names setup with 'redbot-setup'", metavar=None),
 _StoreTrueAction(option_strings=['--owner'], dest='owner', nargs=0, const=True, default=False, type=None, choices=None, help='ID of the owner. Only who hosts Red should be owner, this has serious security implications if misused.', metavar=None),
 _StoreAction(option_strings=['--co-owner'], dest='co_owner', nargs='*', const=None, default=[], type=<class 'int'>, choices=None, help="ID of a co-owner. Only people who have access to the system that is hosting Red should be  co-owners, as this gives them complete access to the system's data. This has serious security implications if misused. Can be multiple.", metavar=None),
 _AppendAction(option_strings=['--prefix', '-p'], dest='prefix', nargs=None, const=None, default=None, type=None, choices=None, help='Global prefix. Can be multiple', metavar=None)]

通过这种方式,您可以看到输入参数如何转换为控制解析和帮助打印的属性。