python - 如何从 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 的论点?
解决方案
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})
动作列表是一个带有名称和帮助键的字典列表。
推荐阅读
- azure - 可以从不同的机器或位置恢复 azcopy 作业吗?
- python - 对重复行求和
- python - Python Django - pgAdmin 应用程序关闭后,带有 Amazon RDS 的 PostgresSQL 数据库关闭
- react-hooks - 使用反应增加值
- javascript - 输入 onChange 处理程序适用于桌面,但不适用于 iOS
- import - 如何避免 Power Query 的参数表中的防火墙阻塞?
- flutter - 如何画半圆
- flutter - 如何创建具有上部固定和下部浮动元素的 SliverAppBar?
- apache-spark - 在 spark 中执行 join 时,是否可以使用 join 语句条件来过滤行而不是 shuffle?
- sql - 来自 BlitzIndex 的 ASP.NET 成员资格表和边界重复键