首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >指定参数以使其成为默认参数。

指定参数以使其成为默认参数。
EN

Stack Overflow用户
提问于 2018-03-31 13:01:48
回答 1查看 52关注 0票数 0

我的代码中有一个标志字典,作为a解析器的一个新参数。因为稍后我需要帮助文本,所以它在一个单独的dict中。

有些参数需要为parser.add_argument传递,但有时不需要。因此,如果它们不需要被传递,那么它们在dict中就等于None。然而,如果我试图通过None,它将认为这是一个新的论点。如果代码等于None,如何使代码不传递指定的参数

代码语言:javascript
复制
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参考中指定。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-31 16:27:59

删除None的辅助函数

代码语言:javascript
复制
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和我在评论中注意到的更正

代码语言:javascript
复制
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对象。它的一些属性可以查看,甚至可以修改。收集您自己的这些对象列表可能很方便。或者,您可以在创建之后使用以下内容查看它们:

代码语言:javascript
复制
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)]

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49588044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档