首页 > 解决方案 > 如何从 ArgumentParser 获取参数列表

问题描述

有没有办法从 ArgumentParser 对象中获取不同的参数?
假设我有以下 ArgumentParser:

parser = argparse.ArgumentParser(add_help=False, allow_abbrev=True)
parser.add_argument("--help", action="store_true", help="Provides help on usage.")
parser.add_argument("-u", "--user", help="A User, could be their tag or User ID.")
parser.add_argument("-hi", "--upper", type=int, default=100, help="The highest stat to include, this is inclusive. Should be an integer type.")
parser.add_argument("-lo", "--lower", type=int, default=0, help="The lowest stat to include, this is inclusive. Should be an integer type.")

# ...

理想情况下,我想要一个这样的列表:

[
    {"name": "help", "help":"Provides help on usage."},
    {"name": "user", "help":"A User, could be their tag or User ID."},
    {"name": "upper", "help":"The highest stat to include, this is inclusive. Should be an integer type."},
    {"name": "lower", "help":"The lowest stat to include, this is inclusive. Should be an integer type."}

    # ...
]

# or even better
[
    Argument,
    Argument,
    Argument,
    Argument

    # where you can use Argument.help or Argument.name
]

我能看到的最好的方法是使用parser.format_help()以获得使用输出,然后将其拆分并解析为正确的格式,但必须有一种不同的方法。

我能做些什么来获得 ArgumentParser 的论点?

标签: pythonargparse

解决方案


parser._actions是 的子类的实例列表Action。每个动作都有一个option_strings属性,它是匹配的字符串列表。您需要提取最长的选项字符串,因为您不希望每个短选项都有单独的结果(例如 -u 和 --user )

actions = []
for action in parser._actions:
    longest = ''
    for option in action.option_strings:
        option = option.lstrip('-')
        if len(option) > len(longest):
            longest = option
    actions.append({'name': longest, 'help': action.help})

动作列表是一个带有名称和帮助键的字典列表。


推荐阅读