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

Specify an argument to make it default

我的代码中有一个标志字典,作为新参数添加到 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

中没有指定

去除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

例如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 returns 您刚刚创建的 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)]

这样您就可以看到输入参数如何转换为控制解析和帮助打印的属性。